我一直不能将此错误Observable赋予Observable Angular 7

问题描述 投票:1回答:1

我正在使用Visual Studio IDE for MAC,我可以构建Angular 7应用程序,但无法在浏览器中运行该应用程序。我在第二个方法中得到错误.Observable <{}>不能分配给Observable

import { Injectable } from '@angular/core';
import { Product } from '../interfaces/product';
import { HttpClient } from '@angular/common/http';
import { shareReplay, flatMap, first } from 'rxjs/operators';
import { Observable} from 'rxjs';


@Injectable({
     providedIn: 'root'
 })

export class ProductService {

  constructor(private http : HttpClient) { }

  private baseUrl: string = "/api/product/getproducts";

  private product$: Observable<Product[]>;

  /*This Method Works Fine */

  getProducts() : Observable<Product[]>
            {

               this.product$ = this.http.get<Product[]> 
               (this.baseUrl).pipe(shareReplay());
               return this.product$;

            }

        /*Error on this Method  */

  getProductById(id : number) : Observable<Product> 
            {
               return this.getProducts().pipe(flatMap(result => result), 
first(product => product.productId == id))
            }

                         }

export interface Product {
            productId?: number;
            name: string;
            description: string;
            outOfStock: boolean;
            price: number;
            imageUrl: string;
        }
angular observable angular7
1个回答
1
投票

根据我对您的评论问题,将您的方法更改为以下编译成功:

  getProductById(id: number): Observable<Product> {
    return this.getProducts().pipe(
      map(products => products.find(product => product.productId === id))
    );
  }

StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.