我有一个 profileComponent,它正在对服务端点进行 GET 调用,如下所示,AparmentService 被注入(inject)到 bootstarp 中,因此没有提供者
@Component({
selector: 'profile',
template: `<h1>Profile Page</h1>
{{userEmail.email}}
{{profileObject | json}}
`,
directives: [ROUTER_DIRECTIVES]
})
export class ProfileComponent implements OnInit {
userEmail = JSON.parse(localStorage.getItem('profile'));
public profileObject: Object[];
constructor(private apartmentService: ApartmentService) {
this.apartmentService = apartmentService;
}
ngOnInit(): any {
console.log(this.userEmail.email); <--This value displays fine in the console
this.apartmentService.getProfile(this.userEmail.email).subscribe(res => this.profileObject = res); <-- getting [] response for this
console.log(JSON.stringify(this.profileObject)); <-- undefined
}
}
服务看起来像这样
@Injectable()
export class ApartmentService {
http: Http;
constructor(http: Http) {
this.http = http;
}
getProfile(userEmail :string){
return this.http.get('/api/apartments/getprofile/:userEmail').map((res: Response) => res.json());
}
}
当我尝试使用参数直接在浏览器中访问端点时,我得到了响应。但不在 Angular 中。
有什么想法吗?
最佳答案
http.get()
是异步的
ngOnInit(): any {
console.log(this.userEmail.email); <--This value displays fine in the console
this.apartmentService.getProfile(this.userEmail.email).subscribe(res => this.profileObject = res); <-- getting [] response for this
// at this position the call to the server hasn't been made yet.
console.log(JSON.stringify(this.profileObject)); <-- undefined
}
当来自服务器的响应到达时 res => this.profileObject = res
被执行。 console.log()
在对服务器的调用甚至被初始化之前进行
改用
ngOnInit(): any {
console.log(this.userEmail.email); <--This value displays fine in the console
this.apartmentService.getProfile(this.userEmail.email)
.subscribe(res => {
this.profileObject = res;
console.log(JSON.stringify(this.profileObject));
});
}
我认为 URL 中的 :userEmail
没有达到您的预期。试试看:
getProfile(userEmail :string){
return this.http.get(`/api/apartments/getprofile/${userEmail}`).map((res: Response) => res.json());
}
关于node.js - Angular2 将参数传递给 web 服务 http GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37474804/