导航后角度数据不会更新

时间:2018-08-20 05:19:16

标签: angular rxjs router

所以我正在使用angular6创建一个帖子系统。问题是当我成功创建帖子并导航回仪表板时,在仪表板的ngOnInit中触发的服务会获取所有帖子,但最新创建的帖子除外。 我确保在成功创建帖子后触发了导航,并且如果刷新页面,它将显示新帖子。

//this is the post creating method in edit component
createArticle(){
    const content = this.contentInput.nativeElement.value;
    this.articleService.create(content, this.uris).then(res => {
      //create article success
      this.router.navigateByUrl('/dashboard');
    }, err => {
      console.log(err);
      this.router.navigateByUrl('/dashboard');
    });
    
//this is part of dashboard component which should show posts
ngOnInit() {
      this.load()  //cannot get the newest post
      //setTimeout(()=>this.load(),100)   --> this is a workaround
      
  }


  load(){
      this.article.getAll().subscribe(
          res => {
              if(res instanceof HttpResponse){
                  console.log(res.body)
                  this.handleArticles(res.body) //show every post except for the lastest one

              }
              
            },
          err => console.log(err)
      )
  }
   
        
         //in the create method in article.service.ts
    return new Promise((resolve,reject) => {
              this.auth.me(header).subscribe((res:UserResponse) => {
                  console.log(res)
                  user_id = res.id;
                  name = res.name;
                  this.reqForCreate(content, uris, user_id, name)
                     .subscribe((e: HttpResponse<any>)=>{
                  
                          resolve();
              
                      }, err=>reject(err));
               },
              err => reject(err))
            })
    
       
    //back end code in the article controller
      public function create(Request $request){
         $this->validate($request, [
             'content' => 'required|string|max:200|min:5',
              'uris' => 'nullable|string',
              'user_id'=>'nullable|integer',
              'user_name'=>'required|string'
          ]);

    $article = Article::create(request(['content', 'uris','user_id', 'user_name']));
    return response()->json($article);

}

public function getAll(){
    return response(Article::all(), 200);
}

以上是代码的一部分。我搜索了一会儿,但找不到答案,也许是因为我不能很好地总结问题,请耐心说英语。 我通过在获取数据之前设置超时来解决该问题。但这不是一个不错的解决方案,对吗? 我以为获取帖子操作比创建帖子更快,但是获取是在创建..成功回调之后触发的,我很困惑,有人可以提示一下吗? 非常感谢!

1 个答案:

答案 0 :(得分:0)

所以我找出了问题所在,这是在前端。在商品服务创建方法中,我使用了承诺来包装可观察的请求以创建新商品。只要observable.subcribe()得到响应,它就会解析。

.subscribe((e: HttpResponse<any>)=>{
                  
       resolve();
              
}, err=>reject(err))

因此该订阅者实际上得到了2个响应:第一个是类型0响应,表示“已发送”,第二个是类型4响应,这是我们想要的。当类型为0时,promise会更早解析。因此,我需要做的是在resolve()之前进行类型检查

.subscribe((e: HttpResponse<any>)=>{
                  if(e.type == 4){
                          resolve();
                  }
}, err=>reject(err))

就是这样。感谢您的关注!

相关问题