Search code examples
angulartypescriptpromisereturnobservable

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?


Solution

  • 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));
    }