在从API返回数据之前,angular 2函数继续运行

时间:2017-07-08 21:41:50

标签: javascript angular typescript angular2-routing

我在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 Class

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 Class

export class HomeUserComponent implements OnInit{

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

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

2 个答案:

答案 0 :(得分:1)

.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()的函数中。

答案 1 :(得分:1)

除非必要,否则应避免在服务中致电{ "apiVersion": "2017-05-10", "name": "nestedTemplate", "type": "Microsoft.Resources/deployments", "resourceGroup": "crossResourceGroupDeployment", "properties": { } } 。让您的服务执行所有逻辑操作,并且只在组件中执行android { ... splits { // Configures multiple APKs based on ABI. abi { // Enables building multiple APKs. enable true // By default all ABIs are included, so use reset() and include to specify that we only // want APKs for x86, armeabi-v7a, and mips. reset() // Specifies a list of ABIs that Gradle should create APKs for. include "x86", "armeabi-v7a", "mips" // Specify that we want to also generate a universal APK that includes all ABIs. universalApk true } } }

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

.subscribe

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

.map