【问题标题】:angular 2 function continue before return data from APIangular 2 函数在从 API 返回数据之前继续
【发布时间】:2017-07-08 21:41:50
【问题描述】:

我在 Angular 2 中遇到问题,该函数继续工作并且不等待从 API 获取数据。

HTTPHelper 类

import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { ReturnResultViewModel } from './ReturnResultViewModel';

export class HttpHelpers {

     _result: any = null;
     _errormsg: any = null;
     _returnResultViewModel: ReturnResultViewModel;    

     constructor(private http: Http) {
         this._returnResultViewModel = new ReturnResultViewModel();    
    }

    postaction(param: any, path: string) {    
        let body = JSON.stringify(param);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(path, body, options)
            .map((m:Response) =>  m.json())    
    }
}

HomeUserService 类

import 'rxjs/add/operator/map';
import { HttpHelpers } from '../../../HttpHelpers';
import { usersHome } from "././Home.users.ViewModel";
import { ReturnResultViewModel } from "../../../ReturnResultViewModel";

import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
Injectable()


export class HomeUsersService extends HttpHelpers {    
    private _UrlLogin: string = "Accounts/getAllUsers";

    constructor( @Inject(Http) private _http: Http) {
        super(_http);    
    }
    private _usersHome: usersHome[];
    getAllUsers(): usersHome[]{

        alert(2);
         this.postaction(null, this._UrlLogin)
            .subscribe(result => 
                this._returnResultViewModel = result);


         if (this._returnResultViewModel == null)
         {
             alert("NULL");
             return null;
         }
         else {
             alert("Has DATA");
             this._usersHome = this._returnResultViewModel.result;
             alert(this._usersHome.length)
             return this._usersHome;
         }



    }
}

HomeUserComponent 类

export class HomeUserComponent implements OnInit{

    _usersHome: [usersHome];
    constructor( private _homeUsersService: HomeUsersService, private _router: Router) {}

   ngOnInit() {
        alert(1);
        var x =  this._homeUsersService.getAllUsers();
   }
}

【问题讨论】:

    标签: javascript angular typescript angular2-routing


    【解决方案1】:

    除非必要,否则您应该避免在您的服务中调用subscribe。让你的服务做所有的逻辑操作,并且只在你的组件中做一个subscribe

    在您的服务中,将您的.subscribe 更改为.map

    export class HomeUsersService extends HttpHelpers {
        private _UrlLogin: string = "Accounts/getAllUsers";
    
        constructor(@Inject(Http) private _http: Http) {
            super(_http);
        }
    
        private _usersHome: usersHome[];
    
        getAllUsers(): usersHome[] {
    
            alert(2);
            this.postaction(null, this._UrlLogin)
                .map(result => {
                    if (result === null) {
                        alert("NULL");
                        return null;
                    } else {
                        alert("HAS DATA");
                        this._usersHome = result.result;
                        alert(this._usersHome.length);
                        return this._usersHome;
                    }
                });
        }
    }
    

    现在,由于您的服务返回了正确映射的 Observable,您可以在组件中处理其余部分:

    export class HomeUserComponent implements OnInit {
    
        _usersHome: [usersHome];
    
        constructor(private _homeUsersService: HomeUsersService, private _router: Router) {
        }
    
        ngOnInit() {
            alert(1);
            this._homeUsersService.getAllUsers()
                .subscribe(users => {
                    //do something to your users.
                    let x = users;
                });
        }
    }
    

    【讨论】:

      【解决方案2】:

      .subscribe() 中的代码是异步的。这意味着它不会立即执行,而是稍后执行。

      如果您的代码 x 取决于异步位的执行,则必须将 x 放在 .subscribe() 部分本身或使用其他机制,如回调或承诺。

      尝试如下:

      getAllUsers(): usersHome[]{
      
          alert(2);
           this.postaction(null, this._UrlLogin)
              .subscribe((result) => {                    // changed here
      
                  this._returnResultViewModel = result;   // changed here
      
      
           if (this._returnResultViewModel == null)
           {
               alert("NULL");
               return null;
           }
           else {
               alert("Has DATA");
               this._usersHome = this._returnResultViewModel.result;
               alert(this._usersHome.length)
               return this._usersHome;
           }
      
      
         }                                               // added this
      }
      

      我将依赖于异步部分 (this._returnResultViewModel = result;) 的代码放在了提供给 .subscribe() 的函数中。

      【讨论】:

        猜你喜欢
        • 2011-08-16
        • 2020-03-01
        • 2020-03-13
        • 1970-01-01
        • 2017-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-24
        相关资源
        最近更新 更多