我有一个angular 2项目,其中有几个组件。
组件之一使用订阅来跟踪成员(即上述的BehaviorSubject)。
当用户单击按钮时,将更新并推送BehaviorSubject的值。
但是,在订阅时,曾经推送的唯一值是原始值(即0)。
Navbar组件是订阅服务器,在CountService中声明BehaviorSubject。
我的CountService:
@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);
}
}
最佳答案
可能是由于单个组件中使用了 providers
数组而发生的。
从各个组件中删除 provides:[CountService]
,并在中声明它rootcomponent's @NgModule
关于angular - BehaviorSubject保持重置为原始值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41910983/