简体   繁体   English

Angular - 在另一个组件中使用由回调设置的服务属性

[英]Angular - Using a service property set by callback in another component

I am trying to use a DataService property myData that is waiting for callback.我正在尝试使用等待回调的DataService属性myData But it is undefined when I call in DataComponent .但是当我调用DataComponent时它是未定义的。 How can I access and use it there?我如何在那里访问和使用它?

export class DataService {
  public myData;

  constructor(private http: HttpClient) {
    this.load().then((data) => {
      this.myData = data
    })
  }

  load() {
    return new Promise((resolve) => {
      this.http.get('https://reqres.in/api/users').subscribe(
        (res: any) => {
          console.log(res.data)
          resolve(res.data)
        },
        (error) => {
          console.log(error);
        }
      )
    })
  }
}
export class DataComponent implements OnInit {
  constructor(private dataService: DataService) {
    this.prepareData();
  }

  prepareData() {
    console.log(this.dataService.myData)
  }

  ngOnInit(): void {
  }
}

Here is the source code: https://stackblitz.com/edit/angular-ivy-kbpdpo这是源代码: https://stackblitz.com/edit/angular-ivy-kbpdpo

You are running into a race condition since this is an asynchronous function.由于这是一个异步 function,因此您遇到了竞态条件。

This change works: https://stackblitz.com/edit/angular-ivy-vf3llg此更改有效: https://stackblitz.com/edit/angular-ivy-vf3llg

Consider reading up on https://angular.io/guide/http考虑阅读https://angular.io/guide/http

Personally, I just have services return raw data and manipulate it elsewhere, but if needed you can tap into the response as I have shown i the updated example.就我个人而言,我只是让服务返回原始数据并在其他地方对其进行操作,但如果需要,您可以利用我在更新示例中展示的响应。

This question and answer are probably really a duplicate of this question...这个问题和答案可能真的是这个问题的重复......

What are pipe and tap methods in Angular tutorial? Angular教程中的pipe和抽头方法是什么?

your load() method is asynchronous, that means that it can return the response after 2 hours, so it will execute your callback after 2 hours, and you are asking myData synchronously which means that you are asking it right now, so it won't work.您的load()方法是异步的,这意味着它可以在 2 小时后返回响应,因此它将在 2 小时后执行您的回调,并且您正在同步询问myData ,这意味着您现在正在询问它,所以它不会不工作。

you have to wait until the answer is returned, in your code there is no chance to accomplish this, so either remove yourData field and just subscribe it into the component, or create BehaviorSubject and emit value to the component您必须等到返回答案,在您的代码中没有机会完成此操作,因此要么删除 yourData 字段并将其订阅到组件中,要么创建BehaviorSubject并向组件发出值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM