简体   繁体   中英

Resolve Http Request on Angular2 before executing code

I've encountered problems trying to resolve an http.post request before doing some other code.

Here's the place:

  getRefresh(token){
    debugger;
    console.log("sono dentro get refresh");
    console.log(token);
    let params = new URLSearchParams();
    params.append('grant_type','refresh_token');
    params.append('refresh_token',token);
    params.append('client_id','web_app');

    let headers = new Headers({'Content-type': 'application/x-www-form-urlencoded; charset=utf-8','Authorization': 'Basic '+btoa("web_app:")});
    let options = new RequestOptions({headers: headers});

    this._http.post('http://localhost:9997/oauth/token',params.toString(),options)
      .map(res => res.json())
      .subscribe(
        data => this.saveToken(data),
        err => alert('Invalid Credentials')
      );
  }

Following the control flow via Browser Console, I've noticed that saveToken method is not executed asap.

The fact is that I need that method for registering some cookies, reused here:

if (!Cookie.get("access_token")) { 
      this.getRefresh(Cookie.get("refresh_token"));
      cookie = Cookie.get("access_token");

    } else {

      cookie = Cookie.get("access_token");
    }

      var headers = new Headers({
        'Content-type': 'application/x-www-form-urlencoded; charset=utf-8',
        'Authorization': 'Bearer ' +  cookie                                 
      });

      var options = new RequestOptions({headers: headers});

      return this._http.get(resourceUrl, options)
        .map((res: Response) => res.text())
        .catch((error: any) => Observable.throw(error().json().error || 'Server error'));

How can I resolve the async problem of observable?

Change your getRefresh(token) method to return the observable and use that in your calling code:

function getRefresh(token) {
    debugger;
    console.log("sono dentro get refresh");
    console.log(token);
    let params = new URLSearchParams();
    params.append('grant_type', 'refresh_token');
    params.append('refresh_token', token);
    params.append('client_id', 'web_app');

    let headers = new Headers({ 'Content-type': 'application/x-www-form-urlencoded; charset=utf-8', 'Authorization': 'Basic ' + btoa("web_app:") });
    let options = new RequestOptions({ headers: headers });

    return this._http.post('http://localhost:9997/oauth/token', params.toString(), options)
        .map(res => res.json())
        .flatMap(
            data => this.saveToken(data),
            err => alert('Invalid Credentials')
        );
}

function getResource() {
    var cookie = Cookie.get("access_token");
    var headers = new Headers({
        'Content-type': 'application/x-www-form-urlencoded; charset=utf-8',
        'Authorization': 'Bearer ' + cookie
    });

    var options = new RequestOptions({ headers: headers });

    return this._http.get(resourceUrl, options)
        .map((res: Response) => res.text())
        .catch((error: any) => Observable.throw(error().json().error || 'Server error'));
}

function callingCodeFunction() {
    if (!Cookie.get("access_token")) {
        this.getRefresh(Cookie.get("refresh_token"))
            .flatMap((result) => {
                getResource();
            });
    } else {
        getResource()
    }
}

*I've not run this code - so there may be errors, but it should serve to demonstrate the principle.

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