我在 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();
}
}
最佳答案
除非必要,否则您应该避免在服务中调用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;
}
});
}
}
现在,由于您的服务返回了正确映射的 Observables,您可以在组件中处理其余部分:
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;
});
}
}
关于javascript - Angular 2函数在从API返回数据之前继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44990995/