简体   繁体   中英

Angular HTTP GET/POST does nothing

I'm using the same code to get/post to my API as I did with my previous applications, but now it doesn't work:

let options_ = {
  method: "get",
  headers: new Headers({
    "Content-Type": "application/json",
    "Accept": "application/json"
  })
};

return this.http.get(url_, options_).flatMap((response_) => {
  return this.processResponse(response_);
})

this code works for me in other applications but in this one doesn't. It doesn't reach the server and in the traffic tab I see no request. I've enabled cors on the server. How do I fix this issue?

A request isn't executed unless you subscribe to the Observable returned by the get function, as shown in the example below:

doGet() {
  return this.http.get(url_, options_).flatMap((response_) => {
    return this.processResponse(response_);
  });
}

yourOtherFunction() {
  doGet().subscribe(result => { 
    // your code 
  });
}

Try by using observables fucntions

Get Method

getFuntion(): Observable<any[]> {

        return this._http.get(this._baseUrl+'/controller/api')
        .map(res => { 
            return res.json().map(item => { 
              return item;
            });
          });
    }

Post Method

postFunction(id, action) {

        let data = {
            id: id,
            action: action
        };   
        let body = JSON.stringify(data)
        let head = new Headers({
            'Content-Type': 'application/json'
        });


        return new Observable(observer => {      
            this._http.post(this._baseUrl+'/controller/api/',
            body , {headers : head})
            .map((res: Response) => res.json())
            .subscribe(res => {                
                observer.next(res);
                observer.complete();
            }); 
        });                

    }

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