2016-05-27 90 views
1

我这是一个GET调用服务端点遵循profileComponent,AparmentService在bootstarp注入,因此没有提供Angular2将参数传递给Web服务HTTP GET

@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中。

任何想法?

回答

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()之前作出服务器调用甚至被initalized

改用

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()); 
} 
+0

只需添加那些大括号?我试过了,没有改变。 – user2180794

+0

对不起,以某种方式移动'console.log(...)'行丢失了。 –

+0

仍然是相同的行为。我认为我在传递参数方面做错了什么。 – user2180794

相关问题