我有类似的东西:
account.component.ts
getCoworker(id:number){
this.userService.getCoworker(id)
.subscribe(
worker => this.worker = worker
)
}
onViewCoworker(id){
this.getCoworker(id);
}
account.component.html
<div *ngIf="viewCoworkers" class="container">
<div class="row">
<div class="col s12">
<ul class="collection">
<a (click)="onViewCoworker(coworker.id)" *ngFor="let coworker of coworkers" class="collection-item avatar valign-wrapper" id="coworker{{coworker.id}}">
<span class="title">{{coworker.name}} {{coworker.surname}}</span>
<p>{{coworker.job}}</p>
</a>
</ul>
</div>
</div>
<div *ngIf="viewCoworker" class="container">
<div class="row">
<div class="col s12 center-align">
<div class="card center-align">
<div class="card-title">{{worker.name}}</div>
</div>
</div>
user.service.ts
getCoworker(id:number):Observable<User[]>{
const token = this.authService.getToken();
let url = 'http://localhost:8000/api/coworker/' + id + '?token=';
return this.http.get(url+token)
.map(res=> res.json())
.catch(this.handleError)
}
json回应
[{"id":25,"name":"lulu","surname":"lu","email":"test@test.com","phone":"0606060606","number":1102,"street":"rue de ketazi","zip":"31200","city":"London","job":"developpeur web","skills":null,"project":"ketaz party","avatarPath":null,"birthDate":null,"inscriptionDate":null,"status":null,"disabledDate":"1970-01-01","role":null,"password":"$2y$10$zyCtW4U73TPy8orLO58yieorKS\/4DezqL.P6VZs66LSYyHuzC9YJK","fidelityPoint":12,"remember_token":null,"created_at":"2017-08-21 19:05:44","updated_at":"2017-08-24 12:59:56"}]
user.servie中的getCoworker工作正常(在postman中返回json) 但是当我在模板中调用onViewCoworker(coworker.id)时,控制台打印:
EXCEPTION: Error in ./AccountComponent class AccountComponent - inline template:154:34 caused by: Cannot read property 'name' of undefined
我试过了{{worker?.name}}:没有错误,但没有数据显示。
不知何故,它不会返回&#34;工人&#34;。 我想我错过了什么?
答案 0 :(得分:0)
在user.service.ts
getCoworker(id: number): Observable < User > {
const token = this.authService.getToken();
let options: RequestOptions = new RequestOptions();
let headers: Headers = new Headers();
//headers.append("key", value);
options.headers = headers;
options.params = new URLSearchParams();
options.params.append("token", token);
let url = 'http://localhost:8000/api/coworker/' + id;
return this.http.get(url, options)
.map((res: any) => res.json() as User)
.catch(err: Response) => Observable.throw(this.handleError /* or method that can use the content of the err variable. 404 page perhaps */ ));
}
&#13;
如果您只希望来自该请求的单个用户对象,则不需要将返回类型作为数组。
它可能已经抛出,因为你的.map()
没有将Json映射到任何东西。它本质上是将Json对象发送到Subscribe()
方法。所以,从理论上讲,你试图从Json中读取.name
。