问题描述
我正在学习Angular,需要您的帮助:)。
我有两个组件list-items和list-item。
- 列表项显示项目列表
- list-item用于添加新的列表项。
当我在列表项上添加列表项并导航回列表项时,共享服务的项目列表中有重复的项目。简而言之,当我添加一个列表项时,我在列表项屏幕中看到多个重复项。用于复制问题的示例项目的GitHub链接为@ https://github.com/ChathaKiran/AngularSharedServiceIssue。下面是我的代码快照。请让我知道如何确保没有重复。
共享服务
const appVerifier = new firebase.auth.RecaptchaVerifier('create-new-user-button',{ size: 'invisible' }) // An element with id="create-new-user-button" must exist
const confirmationResult = await firebase.auth().signInWithPhoneNumber(phoneNumber,appVerifier)
const verificationCode = window.prompt('Please enter the verification code that was sent to your phone.')
const { user } = await confirmationResult.confirm(verificationCode)
列出项目组件
export class AppService {
private listItem = new BehaviorSubject(null);
listItemObservable = this.listItem.asObservable();
private listItems = new BehaviorSubject([] as string[]);
listItemsObservable = this.listItems.asObservable();
updateListItem(_listItem: string) {
this.listItem.next(_listItem);
}
updateListItems(_listItems: string[]) {
this.listItems.next(_listItems);
}
}
列表项组件
export class ListItemsComponent implements OnInit {
_localListItems: string[];
constructor(private appService: AppService){}
ngOnInit(){
this.appService.listItemsObservable.subscribe(_listItems => {
this._localListItems = _listItems;
});
this.appService.listItemObservable.subscribe(_listItem => {
if (_listItem != undefined) {
var allItems = this._localListItems.concat(_listItem);
this.appService.updateListItems(allItems);
}
});
}
}
解决方法
您始终必须取消订阅Observable。
阅读此article并使用ngOnDestroy更新代码,您将在其中从{Observable}中.unsubscribe()
,或添加一些类似.pipe(take(1))
的可管道运算符。
在此处Piepable operators