2016-05-27 91 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

相關問題