Typescript 给出未定义错误的角度可观测服务呼叫
我有一个服务,它进行API调用,重新运行有效用户的集合。 下面给出的是来自服务和组件的代码片段 将响应映射到服务中定义的局部变量时出错-> ValidUserCollection未定义 注意:我的呼叫服务已成功,我的响应状态为200,Ok:true。 唯一的问题似乎是当我将响应映射到服务中定义的局部变量时Typescript 给出未定义错误的角度可观测服务呼叫,typescript,angular-services,http-get,Typescript,Angular Services,Http Get,我有一个服务,它进行API调用,重新运行有效用户的集合。 下面给出的是来自服务和组件的代码片段 将响应映射到服务中定义的局部变量时出错-> ValidUserCollection未定义 注意:我的呼叫服务已成功,我的响应状态为200,Ok:true。 唯一的问题似乎是当我将响应映射到服务中定义的局部变量时 constructor(private http: Http){ this.ValidUsersCollection = []; } GetAllUsers
constructor(private http: Http){
this.ValidUsersCollection = [];
}
GetAllUsers(): Observable<User[]>
{
return this.http.get('http://localhost:8055/api/user/GetAllUsers/', { headers: this.getHeaders() })
.map(this.mapPersons)
}
mapPersons(response:Response): User[]
{
return response.json().map(this.ValidUsersCollection)
}
private getHeaders() {
let headers = new Headers();
headers.append('Accept', 'application/json');
return headers;
}
code from my component
this.userSrv.GetAllUsers()
.subscribe(allusers => this.allUsersCollection = allusers);
有没有关于我可能遗漏了什么或做错了什么的建议
以下是我在服务中定义的方法的服务代码
constructor(private http: Http){
this.ValidUsersCollection = [];
}
GetAllUsers(): Observable<User[]>
{
return this.http.get('http://localhost:8055/api/user/GetAllUsers/', { headers: this.getHeaders() })
.map(this.mapPersons)
}
mapPersons(response:Response): User[]
{
return response.json().map(this.ValidUsersCollection)
}
private getHeaders() {
let headers = new Headers();
headers.append('Accept', 'application/json');
return headers;
}
code from my component
this.userSrv.GetAllUsers()
.subscribe(allusers => this.allUsersCollection = allusers);
试着这样做:
let ValidUsersCollection : User[] = [];
constructor(private http: Http){}
GetAllUsers(): Observable<User[]> {
return this.http.get('http://localhost:8055/api/user/GetAllUsers/', { headers: this.getHeaders() })
.map(res =>{
return res.json().map(items => { this.ValidUsersCollection = items });
});
}
仍然错误是一样的。。。我没有定义。。请注意,我不能将ValidUserCollection声明为var或let,因为这是类成员。。。类成员可以是private/public或nothing…@user9401912您应该知道的第一件事是您不应该在组件中使用已定义的服务数组,在服务中,您应该只编写http请求,在组件订阅中获取结果并将其映射到数组中。我没有将服务成员使用到我的组件中。。。正如您在上面的组件代码中所看到的,我正在调用服务方法并订阅对本地组件变量的响应。。。不知道我还做错了什么