2017-10-16 87 views
0

我構建了一個服務,它從API可觀察數據獲取特定的ID。該服務正在工作,如果我從服務類的console.log(數據),但我無法獲取我的組件中的數據。從API服務角度獲取數據4

See the console

服務:

getSpecificStory(storyId) { 
    return this.getToken() 
     .map(idToken => { 
     let headers = new Headers(); 
     headers.set('user_token', idToken) 
     return this.http 
      .get(`${this.apiUrl}/stories/${storyId}`, { headers: headers }) 
      .subscribe((res: Response) => { 
      const data = res.json(); 
      console.log(data) 
      return data; 
      }); 
     }) 
     .catch(this.handleError); 
    } 

組件:

export class StoryModalComponent implements OnInit { 
    story: any; 
    storyId: any; 
    hitsArray: Array<Object>; 

    constructor(private storiesService: StoriesService, private route: ActivatedRoute) { 
    } 

    ngOnInit() { 
    this.route.params 
     .subscribe(
     params => { 
     this.storyId = params['storyId'] 
     }) 
    console.log(this.storyId) 
    this.getStoryObject(); 
    } 


    getStoryObject() { 
    console.log(this.storyId) 
    this.storiesService.getSpecificStory(this.storyId) 
     .subscribe(
     (data) => { 
     this.story = data; 
     console.log(this.story) 
     }) 
    } 
} 
+0

如何做你的組件的外觀? – Sajeetharan

+0

就像我發佈的?你的意思是HTML?順便說一下,不要介意「getToken()」函數 - 它只是用於在Firebase後端獲取用戶的id_token。 – byblix

回答

1

您正在尋找flatMap運算符而不是map。

getSpecificStory(storyId) { 
    return this.getToken() 
     .flatMap(idToken => { 
      let headers = new Headers(); 
      headers.set('user_token', idToken) 
      return this.http 
       .get(`${this.apiUrl}/stories/${storyId}`, { headers: headers }) 
     }); 
    }) 
} 

.flatMap希望你返回一個observable(你的情況this.http.get(...))。現在getSpecificStory方法返回一個observable。所以,你的在你的組件訂閱

this.storiesService.getSpecificStory(this.storyId) 
    .subscribe(
     (data) => { 
      this.story = data; 
      console.log(this.story) 
     }) 

這是當你鏈接相關的可觀察的常用方法(您的火力爲gettoken()方法和你this.http.get())

+2

是啊,這就是訣竅!我仍然在學習RxJs lib,所以非常感謝你! – byblix

1

你必須爲了返回觀察到的用戶在comonent訂閱方法。

getSpecificStory(storyId) { 
return this.getToken() 
    .map(idToken => { 
    let headers = new Headers(); 
    headers.set('user_token', idToken) 
    return this.http 
     .get(`${this.apiUrl}/stories/${storyId}`, { headers: headers }) 
     .map((res: Response) => res.json()); 
     .catch(this.handleError); 
    }) 
    .catch(this.handleError);} 
+0

除了您使用「地圖」之外,我沒有看到與我的區別?如果您查看服務,我將以「返回數據」的形式返回數據; – byblix