Angular2将参数传递给Web服务http GET

时间:2016-05-27 04:21:16

标签: node.js rest http angular

我有一个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());
    } 
}

当我尝试使用参数直接在浏览器中点击端点时,我得到了响应。但不在Angular内。

任何想法?

1 个答案:

答案 0 :(得分:2)

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         
}

执行来自服务器arives 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并不是您所期望的。请尝试改为:

getProfile(userEmail :string){
   return this.http.get(`/api/apartments/getprofile/${userEmail}`).map((res: Response) => res.json());
} 
相关问题