早上好,我想请您检查一下这段代码,并帮助我找出变量itemCount在about.component.html中没有显示任何值但在home.component.html中都没有任何作用的错误之处。我只想在about.component.html中显示itemCount,所以我尝试使用EventEmittent方法。这是代码。
Home.component.ts
export class HomeComponent implements OnInit {
itemCount : number = 0; ---here variable in home component ok
btnText: string = 'Add an item';
goalText: string = 'My first life goal';
goals = [];
@Output()sharedItemCount = new EventEmitter<number>(); -- own event
created
share(){ ---method the invokes own event
this.sharedItemCount.emit(this.itemCount);
}
constructor(private _data: DataService) { }
ngOnInit() {
this._data.goal.subscribe(res =>this.goals = res);
this.itemCount = this.goals.length;
this._data.changeGoal(this.goals);
this.share(); --running method to invoke changes with itemCount variable
}
addItem(){
this.goals.push(this.goalText);
this.goalText = '';
this.itemCount = this.goals.length;
this._data.changeGoal(this.goals);
this.share();--running method to invoke changes with itemCount variable
}
removeItem(i){
this.goals.splice(i,1);
this.itemCount = this.goals.length;
this._data.changeGoal(this.goals);
this.share();--running method to invoke changes with itemCount variable
}
这是About.component.html中的实现,我想在其中查看itemCount的值。
<p (sharedItemCount) = "onShareItemCount($event)">({{itemCount}})</p> --receiving own event that invokes onShareItemCount method and passing them value itemCount and also them showing variable itemCount in brackets
这是About.component.ts中的实现
export class AboutComponent implements OnInit {
goals: any;
itemCount : number; --variable
constructor(private route: ActivatedRoute, private router: Router, private
_data: DataService) {
this.route.params.subscribe(res => console.log(res.id));
}
ngOnInit() {
this._data.goal.subscribe(res =>this.goals = res);
}
onShareItemCount(itemCount: number){--method that set up localvariable the
same as passed through event
this.itemCount = itemCount;
}
答案 0 :(得分:0)
@Output
中的sharedItemCount
事件发射器HomeComponent
是无用的,不需要因为您已经在使用共享服务({ {1}})。
将您的_data: DataService
文件更改为:
About.component.html
在<p>({{itemCount}})</p>
文件中,将About.component.ts
函数更改为:
ngOnInit
您的ngOnInit() {
this._data.goal.subscribe(res => {
this.goals = res;
this.itemCount = res.length;
});
}
函数使用rxjs Observable对目标对象的每次更改进行更新,从而更新了模板。只是不要忘记在ngOnInit
上取消订阅。