在 angular 中将数据从服务解析到组件

Parsing data from service to component in angular

在我的服务中我打了一个电话:

    this.potentialOrganizations(currentNode.id)
      .subscribe(data => {
        console.log('consoling the org data!!!!!!!  '  + JSON.stringify(data))
        this.potentialOrgData = [];
        this.potentialOrgData = data;
        this._potentialOrgs.onNext(true);
      })

数据控制台很好,如您所见,我尝试使用可观察的方法,但由于某种原因它不起作用!

我可能需要一种新的方法来调用数据,正如我在我的组件中所说的那样html我有这个:虽然它不起作用:

<ul *ngIf="this.engagementService.potentialOrgData.length > 0">
  <li *ngFor="let org of this.engagementService.potentialOrgData">
     <p class="listedOrgs">{{ org.name }}</p>
  </li>
 </ul>

在我的组件中我有这个:

  ngOnInit(): void {
this.engagementService.potentialOrgs$.subscribe(
  (data) => {
    if (data) {
      console.log('are we hitting here inside the potentialORG DATA!??!?!?!!?!?')
      this.potentialOrganizations = this.engagementService.potentialOrgData;
    }
  }
)
this.potentialOrganizations = this.engagementService.potentialOrgData;
  }

它没有安慰,即使在我的服务中我设置了可观察的东西:

  private _potentialOrgs = new BehaviorSubject<boolean>(false);
  public potentialOrgs$ = this._potentialOrgs.asObservable();

我在想也许我需要改用@input?但如何正确地做到这一点?

您可以通过尝试以下操作使这里的操作更简单一些。如果 potentialOrgData 是从服务中的订阅设置的,它将保持新鲜,因为订阅保持打开状态。您将可以直接在服务中使用变量。

public requestedData = [];

public ngOnInit(): void {
    this.requestedData = this.engagementService.potentialOrgData;
}

在您的模板中。

<ul *ngIf="requestedData.length">
  <li *ngFor="let org of requestedData">
    <p class="listedOrgs">{{ org.name }}</p>
  </li>
</ul>

Behaviour Subjects 和 Observable 的功能非常强大,但并不总是必要的。