簡體   English   中英

Angular2將參數傳遞到Web服務http GET

[英]Angular2 Passing parameters to web service 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());
    } 
}

當我嘗試使用參數直接在瀏覽器中命中端點時,得到響應。 但不在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執行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());
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM