Angular Http不起作用。混合使用Promise和Observable方法。

4

我正在尝试从Angular将数据发布到后端Node.js文件。在表单提交后,以下函数被调用:

cmdSubmit() : void 
{
       console.log(this.cli);
       this.Cliservice.postdata(this.cli)
                      .then(clidata  => this.clidata.push(clidata),
                            error =>  this.errorMessage = <any>error);

}

postdata函数的代码:

postdata(obj: any): Promise<any> {
    alert('hello');
    let body = JSON.stringify({ obj });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.runUrl, body, options)
                    .map(this.extractData)
                    .catch(this.handleError);

    /*return this.http.post(this.runUrl, body, options)
                      .map(this.extractData)
                      .catch(res => {
             // do something

             // To throw another error, use Observable.throw
             return Observable.throw(res.json());
      });*/


    }

    private extractData(res: Response) {
       let body = res.json();
       return body.data || { };
    }

private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
                  error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
 }

}

但是这里什么也没有发生。我没有收到任何错误信息。你能否提供一些建议?

2个回答

9

每个返回ObservableHttp函数必须附带一个.subscribe()方法。如果你忘记添加这个方法,请求将不会被执行。所以请为每个函数添加.subscribe()方法。

如评论中所述,你正在使用两种方法:Promise风格Observable风格,因此我建议您使用一种通用风格。

this.http.post(this.runUrl, body, options)
         .map(this.extractData).subscribe(/*here your parameters*/);

1
他还混淆了ObservablePromise,而没有转换为Promise - Maximilian Riegler
1
@rinukkusu 是的,他需要使用一种通用的风格。 - Suren Srapyan
只是告诉你这样你可以改进你的回答,以便纠正他所有的错误 :) - Maximilian Riegler

3

@Suren提到的是完全正确的。另外,您也可以使用toPromise()方法直接将其转换为Promise对象:

return this.http.post(this.runUrl, body, options).toPromise();

为此,您需要导入以下内容。
import 'rxjs/add/operator/toPromise'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接