gpt4 book ai didi

Angular2-OnInit : Values returned from Service' subscribe function does not get assigned to Component field/s

转载 作者:太空狗 更新时间:2023-10-29 17:19:00 25 4
gpt4 key购买 nike

我正在试用 Angular2 并一直在学习他们的教程。

我目前有一个从 json 服务器获取数据的服务:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';

import { User } from './user';

@Injectable()
export class UserService {
constructor(private http: Http) {}

private usersUrl = 'http://localhost:3000/users';

getUsers(): Observable<User[]> {
return this.http.get(this.usersUrl) //the request won't go out until something subscribes to the observable
.map(this.extractData)
.catch(this.handleError); // pass an error message back to the component for presentation to the user but only if we can say something the user can understand and act upon
}

private extractData(response: Response) {
if (response.status < 200 || response.status >= 300) {
throw new Error('Bad response status: ' + response.status);
}
let body = response.json(); // parse JSON string into JavaScript objects

return body.data || { };
}

private handleError (error: any) {
// In a real world app, we might send the error to remote logging infrastructure before returning/sending the error
let errMsg = error.message || 'Server error'; // transform the error into a user-friendly message

return Observable.throw(errMsg); // returns the message in a new, failed observable
}

}

还有我的组件:

import { Component, OnInit } from '@angular/core';

import { User } from '../common/user/user';
import { UserService } from '../common/user/user.service';

@Component({
selector: 'app-nav',
templateUrl: '/app/nav/nav.component.html',
styleUrls: ['/app/nav/nav.component.css']
})
export class NavComponent implements OnInit {
errorMsg: string;
users: User[];

constructor(private userService: UserService) { }

getUsers() {
this.userService
.getUsers()
.subscribe(
function(users) {
console.log('users ' + users);
this.users = users;
console.log('this.users ' + this.users);
}, function(error) {
console.log('error ' + error);
});
// users => this.users = users,
// error => this.errorMsg = <any>error);
}

ngOnInit() {
this.getUsers();
console.log('ngOnit after getUsers() ' + this.users);
}
}

我的问题是,在 getUsers() 调用完成后,从订阅函数返回的数据没有传递/分配给我的组件属性“用户”。我知道数据从服务方法调用返回到组件,因为我能够在 userService().getUsers 方法中记录数据。奇怪的是,我的 ngOnInit 上的 console.log 调用在我的 getUsers 方法中的 console.logs 之前首先打印在我的开发控制台上,尽管我首先调用了 getUsers:

  ngOnInit() {
this.getUsers();
console.log('ngOnit after getUsers() ' + this.users);
}

开发控制台截图:

最佳答案

这是因为 this.getUsers()this.userService.getUsers().subscribe(...) 只安排调用来发出请求服务器。最终,当来自服务器的响应到达时(console.log('ngOnit after getUsers() ' + this.users); 甚至在调用服务器之前就已经执行了)然后你的功能传递给 subscribe() 被执行。

这应该做你想做的:

  getUsers() {
return this.userService
.getUsers()
.map(
(users) => {
console.log('users ' + users);
this.users = users;
console.log('this.users ' + this.users);
})
.catch((error) => {
console.log('error ' + error);
throw error;
});
// users => this.users = users,
// error => this.errorMsg = <any>error);
}

ngOnInit() {
this.getUsers().subscribe(_ => {;
console.log('ngOnit after getUsers() ' + this.users);
});
}

getUsers() 中,我使用 map() 而不是订阅,因此我们可以稍后订阅,以便能够在响应到达时执行代码。

然后在 ngOnInit() 中我们使用 subscribe() (subscribe() 是必须的,否则 http.get () would never be executed) 并传递我们希望在响应到达时执行的代码。

我还将 function () 更改为 () =>。这样 this 在下面的代码块 () => { ... } 中工作,否则它不会。

不要忘记添加

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

否则这些运算符将不会被识别。

关于Angular2-OnInit : Values returned from Service' subscribe function does not get assigned to Component field/s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37230545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com