2017-10-07 118 views
2

我有一個Web應用程序。在我的右側欄中,我有3個帖子。 當我點擊後,我有一個導航:角ngOnInit - 刷新所需

this.router.navigate(['../post', this.post.id]); 

有一個後檔組件將接管。 此組件具有一個函數,該函數可以從使用指定標識獲取我的帖子的服務調用函數。現在,我將在我的內容區域(屏幕的左側部分)中看到該帖子的所有詳細信息。該函數(獲取我的文章)僅在Post Profile組件的ngOnInit中調用。

如果我從我的右邊欄另一篇文章點擊,我可以看到URL的變化但得到我的職位是不是叫和我的內容區域的細節後不改變功能。 如果我現在刷新頁面,我可以看到我想要的帖子,一切正常。

我有我的功能.subscribe,有沒有什麼幫助。

我看不到的問題。

這是我PostProfileComponent

 constructor(postsService: PostsService, route: ActivatedRoute) { 
    this.postsService = postsService; 

    this.routeSubscription = route.params 
     .subscribe((params: any) => { 
      this.postId = params['id']; 
     }); 
} 

public getPostById(id: any): void { 
    this.postsService.getPostById(id) 
     .map((response: Post) => { 
      this.post = response; 
      console.log(this.post); 
     }) 
     .catch((error: any) => { 
      return error; 
     }) 
     .subscribe(); 
} 

ngOnInit(): void { 
    this.getPostById(this.postId); 
} 
+0

你真的必須展示你的實際代碼,沒有人能猜到你的代碼是怎樣的。 [如何創建一個最小,完整和可驗證的示例](https://stackoverflow.com/help/mcve) – Alex

回答

1

在您的文章輪廓組件的ngOnInit方法你已經訂閱ActivatedRouteparams觀察到。

subs1: Subscription; 
    constructor(private route: ActivatedRoute){} 

    ngOnInit() { 
    this.subs1 = this.route.params 
     .subscribe((params: Params) => { 
      const postId = params['id'] ? +params['id'] : ''; 
      if(postId){ 
       // call the function (that gets the post) 
      } 
     }); 
    } 
+0

你怎麼知道OP的代碼看起來不是這樣?問題可能在任何地方,這就是爲什麼我要求代碼。也許你是對的,誰知道。 – Alex

+0

我認爲他想要通用解決方案,而這正是我試圖在此給出的。但是,如果@Marian給我們一些他實現的代碼,那麼我會相應地更新我的答案。 – asmmahmud

+0

@Marian,不客氣。如果我的解決方案有效,那麼如果您接受我的解決方案作爲正確答案,對他人會有所幫助。 – asmmahmud