Angular共享服务-将项目添加到列表时,共享服务正在复制数据

问题描述

我正在学习Angular,需要您的帮助:)。

我有两个组件list-items和list-item。

  1. 列表项显示项目列表
  2. 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

了解更多

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...