Angular 1.x $q to Angular 2.0 beta

2019-05-14 10:35发布

问题:

Wanted to convert following service to Angular 2 Service. I am using google api here. The main problem I am getting is to returning the Promise as its not similar as Angular 1.x.

 getLoginStatus: function () {
      var deferred = $q.defer();
      gapi.auth.authorize({client_id: dataStore.getData('CLIENT_ID'), scope: dataStore.getData('SCOPES'), immediate: true},function(response){
      var res = {};
           res = response;
           deferred.resolve(res);
      });
      return deferred.promise;
 }

回答1:

Angular 2 uses RxJS 5 Observables for this:

Here is a 1:1 translation of your code:

getLoginStatus: function () {
      return new Observable(function(observer) {
      gapi.auth.authorize({client_id: dataStore.getData('CLIENT_ID'), scope: dataStore.getData('SCOPES'), immediate: true},function(response){
           observer.next(response);
           observer.complete();
      });
 }