如何在 Angular2 中对成功的 HTTP 请求使用回调函数

How to use Callback function on successful HTTP request in Angular2

我是 Angular2 的新手。我参考了官方网站上的英雄教程,并根据我的要求在Angular2中为HTTP post 请求编写了以下代码。我习惯于 java-script 并且我使用 AJAX 调用来与 Web 服务器交互,在 javascript-AJAX 调用中我们可以在成功时执行一些功能 AJAX 调用(回调函数)。我如何在 angular2 中实现它?我也想使用警报。在每个调用的 success/fail 上显示一个警告框,说明其成功或失败。

@Injectable()
export class LicenceService {
constructor(private http: Http) {}
private headers = new Headers({'Content-Type': 'application/json'});
/* URL to web api*/
private licenceUrl = 'http://localhost:5000/***/****/installation/uploadLicense';  



sendData(key: string){
    return this.http
        .post(this.licenceUrl, key, this.headers)
        .toPromise()
        .then(res => res.json().data)
        .catch(this.handleError);
}
private static handleError (error: any) {
    console.log(error);
    return Promise.reject(error.json());
}

您需要的一切都已在您的代码中

sendData(key: string){
    return this.http
        .post(this.licenceUrl, key, this.headers)
        .toPromise()
        .then(res => {
           res.json().data;
           // code here is executed on success
         })
        .catch(this.handleError);
}

或对于来电者

this.sendData(somekey).then(result => /*put after after success code here */);

尽管您的问题已经得到解答,但这是另一种将服务和回调逻辑分开的方法。我通过使用 subscibeObservable

实现了它

这是我的question.compnent.ts

    ngOnInit() {
               this.getQuestions();
    }        
    getQuestions() {
        this.yourService.getQuestions()
            .subscribe(
            data => this.displayData = data,
            error => this.errorMessage = <any>error,
            () => { 
                  //this gets called on completion, callback code comes here
                  } 
            );
    } 

还有我的 question.service.ts 负责 HTTP 请求部分

   getQuestions(): Observable<DisplayData[]>{
      const endPoint = 'http://localhost:3000/yourApi';
      return this.http.get(endPoint).map((response: Response) => response.json());
}

注意:this.displayData是一个DisplayData[]类型的变量,在Service中用作observable。

抱歉这么久 post。干杯:)