Search code examples
javascriptangularangular4-httpclient

ERROR TypeError: subscribe is not a function


I am trying to get value from array based on some element and then getting the exact matching element. But somehow i am facing this error for in this function getProduct(name1: string), i have imported map already. Help will be much appreciated. this.searchProduct(...).subscribe is not a function

 products: Product[] = [];
 product: Product;

 searchProduct(name2: string): Observable<Product[]> {
    var config = {
        headers: {
            'Content-Type': 'application/json'
        }
    };
    const ans = name2;
    let obj = { name_product: ans }
    let body = JSON.stringify(obj);
    let header = new HttpHeaders();
    header = header.append('Content-Type','application/json');
    return this.httpClient.post('postRestService', body, config).subscribe(res => {
        this.products = res;
        console.log(this.products);
    })
 }

  getProduct(name1: string): Observable<Product> {
   return this.searchProduct(name1).subscribe(products => 
   products.find(product => product.name1 == name1));
 }

Solution

  • The http service changed from angular 2 to angular 4. In angular 4 you don't need map:

    products: Product[] = [];
     product: Product;
    
     searchProduct(name2: string): Observable<Product[]> {
        var config = {
            headers: {
                'Content-Type': 'application/json'
            }
        };
        const ans = name2;
        let obj = { name_product: ans }
        let body = JSON.stringify(obj);
        let header = new HttpHeaders();
        header = header.append('Content-Type','application/json');
        this.http.post('postRestService', body, config).subscribe(res => {
            this.products = res;
            console.log(this.products);
        })
     }
    
      getProduct(name1: string): Observable<Product> {
       return this.searchProduct(name1).subscribe(products => products.find(product => product.name1 == name1));
     }