Angular2将parameter passing给Web服务http GET
我有一个profileComponent正在进行GET调用服务端点如下,AparmentService注入到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()); } }
当我试图用参数直接在浏览器中点击terminal时,我得到了答复。 但不在Angular中。
有任何想法吗 ?
http.get()
是asynchronous的
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)); }); }
我认为:userEmail
中的:userEmail
没有做你期望的。 改为:
getProfile(userEmail :string){ return this.http.get(`/api/apartments/getprofile/${userEmail}`).map((res: Response) => res.json()); }