【问题标题】:Angular ngOnInit - Refresh NeededAngular ngOnInit - 需要刷新
【发布时间】:2018-03-19 05:23:21
【问题描述】:

我有一个网络应用程序。在我的右侧栏中,我有 3 个帖子。 当我点击一个帖子时,我有一个导航:

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

有一个帖子配置文件组件将接管。 这个组件有一个函数,它从一个服务中调用一个函数,该函数用指定的 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);
}

【问题讨论】:

标签: angular angular2-routing angular2-services ngoninit


【解决方案1】:

在您的 Post Profile 组件的 ngOnInit 方法中,您必须订阅 ActivatedRoute params Observable。

  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)
             }
         });
  }

【讨论】:

  • 你怎么知道OP的代码不是这样的?问题可能在任何地方,这就是我要求代码的原因。也许你是对的,谁知道呢。
  • 我认为他想要通用解决方案,这就是我试图在这里给出的。但是,如果@Marian 给我们一些他实现的代码,那么我会相应地更新我的答案。
  • @Marian,不客气。如果我的解决方案有效,那么如果您接受我的解决方案作为正确答案,将对其他人有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多