Angular HTTP GET / POST不执行任何操作

时间:2018-05-23 16:57:37

标签: angular

我使用相同的代码来获取/发布到我的API,就像我之前的应用程序一样,但现在它不起作用:

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

这个代码在我的其他应用程序中适用,但在这个代码中没有。它没有到达服务器,在流量选项卡中我看不到请求。我在服务器上启用了cors。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

除非subscribe Observable函数返回get,否则不会执行请求,如下例所示:

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

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

答案 1 :(得分:1)

尝试使用observables fucntions

获取方法

getFuntion(): Observable<any[]> {

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

发布方法

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

    }
相关问题