Angular 6 多次为 Observable 调用 subscribe()

til*_*ias 2 typescript angular

我有两个组件:NewItemComponent 和 ListComponent。当我在相应的组件内创建新项目时,我会通知 ListComponent 以便它可以刷新它的数据模型:

export class NewItemComponent implements OnInit {

  constructor(private itemService: ItemService, private notificationService: NotificationService) {
  }

  ngOnInit() {
  }

  createNewItem(item: Item) {
    this.itemService.persist(item).subscribe((response: Item) => {
      console.log(response);
      this.notificationService.notifyNewItemHasBeenCreated(response);
    });
  }
}


export class ListComponent implements OnInit {

  items: Item[];

  constructor(private listService: ListService, private notificationService: NotificationService) {
  }

  ngOnInit() {
    this.loadItems();

    this.notificationService.item$.subscribe((item) => {
      if (item != null) {
        this.loadItems();
      }
    })
  }

  loadItems(){
    this.istService.getItems().subscribe((data: Item[]) => {
      this.items= data;
      console.log(this.items);
    });
  }
}


@Injectable({
  providedIn: 'root'
})
export class NotificationService {

  private _item: BehaviorSubject<Item> = new BehaviorSubject<Item>(null);
  public  item$ = this._item.asObservable();

  constructor() {
  }

  notifyNewItemHasBeenCreated(item: Item) {
    this._item.next(item);
  }
}
Run Code Online (Sandbox Code Playgroud)

让我担心的是loadItems()多次调用subscribe()。这是可以的还是有更好的方法根据通知重新获取项目?

  loadItems(){
    this.listService.getItems().subscribe((data: Item[]) => {
      this.items= data;
      console.log(this.items);
    });
  }
Run Code Online (Sandbox Code Playgroud)

ListService 返回 Observable:

export class ListService {

  basePath = 'my-api.com';
  apiPath = "item";

  constructor(private httpClient: HttpClient) {
  }

  getItems(): Observable<Item[]> {
    return this.httpClient.get<Item[]>(this.basePath + '/' + this.apiPath);
  }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢,任何帮助将不胜感激。

Mic*_*ael 8

作为实验,如果您执行以下操作:

this.httpClient.get("<some url>")
  .subscribe({
    next: () => {
      console.log("received response")
    },
    error: err => {
      console.log("error occurred")
    },
    complete: () => {
      console.log("subscription completed")
    },
  })
Run Code Online (Sandbox Code Playgroud)

你应该看到:

received response
subscription completed
Run Code Online (Sandbox Code Playgroud)

这意味着每个 Web 请求的 observable 会在请求完成后完成,因此不要取消订阅是安全的,因为这会在 observable 完成时自动完成。