简体   繁体   中英

Add Promise return type to method in Angular

I have the following method which returns an array of TreeNodes

  basketItemNodes: TreeNode[] = [];

  getBasketItems() {
    this.basketService.getAllBasketItems()
      .subscribe(
        res => {
          this.basketItemNodes = <TreeNode []> res;            
        },
        err => {
          console.log(err);
        }
      );
      return this.basketItemNodes;
  }

How can I change the return type to a Promise or Observable ?

If you want to return Observable , then do not subscribe to it here. Instead you could simply map the response to <TreeNode []> and return.

basketItemNodes: TreeNode[] = [];

getBasketItems() {
    return this.basketService.getAllBasketItems()
      .pipe(map(res => this.basketItemNodes = <TreeNode[]> res));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM