在我刷新页面之前,角度不显示创建的对象

时间:2017-04-03 19:01:59

标签: node.js mongodb angular express mean-stack

请帮助,我有一个消息服务,它从数据库中获取消息并在用户配置文件页面上显示它们。当我创建或删除邮件时,我只能在刷新浏览器时看到更改。

在我应用过滤器按ID排序之前,页面会动态更新,为什么过滤器会取消绑定我的消息数组?

个人资料组件:

    export class ProfileComponent implements OnInit {

    user: User;
    userId: any;
    messages: any;  

    constructor(private authService: AuthService, private messageService: MessageService) {}

    ngOnInit() {
      this.authService.getUser().subscribe(
        (user: User) => {
        this.user = user;
        this.userId = user.userId;
        }
      );
       this.messageService.getMessages()
      .subscribe(
          (messages: Message[]) => {
            this.messages = messages.filter(x => x.userId == this.userId);
            //this.messages = messages; //this works perfect, but shows all users messages
          }
      );
    }
}

2 个答案:

答案 0 :(得分:1)

似乎您的第一个API调用(getUser方法)花费了更多时间,它在getMessages方法之后完成。 你应该以某种方式使他们依赖。您可以使用getUser方法将toPromise Observable转换为承诺。

ngOnInit() {
  this.authService.getUser()
  .toPromise()
  .then(
     (user: User) => {
        this.user = user;
        this.userId = user.userId;
     }
  )
  .then(() => {
      this.messageService.getMessages()
      .subscribe(
         (messages: Message[]) => {
            this.messages = messages.filter(x => x.userId == this.userId);
         }
      );
  });
}

答案 1 :(得分:0)

将您的代码更改为:

messages: Array<any> = [];  
this.authService.getUser().subscribe(
        (user: User) => {
        this.user = user;
        this.userId = user.userId;
        this.messageService.getMessages()
              .subscribe(
                  (messages: Message[]) => {
                    this.messages = messages.filter(x => x.userId === this.userId);
                    //this.messages = messages; //this works perfect, but shows all users messages
                  }
              );
        }
      );

你只需要嵌套其他的observable,所以一旦第一次完成它就会被调用。