Angular 6: unable to make http request

前端 未结 2 1473
孤街浪徒
孤街浪徒 2021-01-26 11:12

In my angular application, I am trying to make the http post request to the spring restful API.. but I could not succeed.. I am not getting any error response in the browser con

相关标签:
2条回答
  • 2021-01-26 11:29

    You missed the subscription. If you have declared addToCart in service and want to handle API response in component modify code as:

    service

    addToCart(productId: number, quantity: number) {
        let data = { 
            "dealerId": 9, 
            "createdBy": "-1", 
            "productId": productId, 
            "quantity": quantity
        }
        const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
        console.log("--------order.service.ts----------addToCart()-------productId:"+productId+":------quantity:"+quantity);
        return this.http.post('http://localhost:8080/order/addtocart', 
                  JSON.stringify(data), 
                  {headers: headers})
                  .pipe(catchError(this.errorHandlerService.handleError));
    }
    

    component subscribe service method

    this.service.addToCart(2, 4).subscribe(res => {
        console.log(res); // Response from API
    })
    
    0 讨论(0)
  • 2021-01-26 11:33

    You are not subscribing to the this.http.post(...) function, which returns an observable.

    An observable does nothing until you subscribe to it, so you code should be:

    addToCart(productId: number, quantity: number) {
        const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
    
        this.http.post('http://localhost:8080/order/addtocart', 
              '{ "dealerId": 9, "createdBy": "-1", "productId": productId, "quantity": quantity}', 
              {headers: headers})
              .pipe(catchError(this.errorHandlerService.handleError))
              .subscribe(data => {
                  // Handle the updated data here.
                  console.log(data);
              });
    }         
    

    Alternatively you can use an async pipe to handle the subscription for you, if you get any data back which can be used in a view directly.

    0 讨论(0)
提交回复
热议问题