我有一个 angular 2 项目,其中有几个组件。其中一个组件使用订阅跟踪成员(即前面提到的 BehaviorSubject)。
当用户单击按钮时,BehaviorSubject 的值会更新并推送。
但是,在订阅时,唯一推送的值是原始值(即 0)。
Navbar 组件是订阅者,其中在 CountService 中声明了 BehaviorSubject。
我的计数服务:
@Injectable()
export class CountService {
private count:number;
public countObservable:BehaviorSubject<number>;
public savedItems = { campaigns: [], news: [] };
constructor (private http: Http) {
this.count=0;
this.countObservable = new BehaviorSubject<number>(this.count);
this.countObservable.next(this.count);
}
keep(keepId: string, type: string){
!!this.savedItems[type].length ?
this.savedItems[type].find(i => i == keepId).length ?
console.log('exist') : this.keepInSavedItems(keepId, type)
this.keepInSavedItems(keepId, type);
}
keepInSavedItems(keepId, type){
this.savedItems[type].push(keepId);
this.count++;
this.countObservable.next(this.count);
}
}
我的导航栏组件:
@Component({
selector: 'navbar',
templateUrl: './navbar.component.html',
providers: [ CountService ]
})
export class NavigationbarComponent implements OnInit {
count:number;
constructor(public countService: CountService){
this.count=0;
}
ngOnInit() : void {
this.countService.countObservable.subscribe( count => this.count=count);
}
}