【问题标题】:Angular component communication - using ngIf with booleans from a serviceAngular 组件通信 - 使用 ngIf 和来自服务的布尔值
【发布时间】:2020-02-27 08:11:22
【问题描述】:

我有 2 个同级组件,如果响应成功,我会显示 API 结果,如果出现 API 错误,则会显示 API 失败错误消息。如果两个组件中都有 API 失败,我只需要显示 1 条 API 失败错误消息。我设法做到了这一点,并且我使用了一项服务来定义布尔值并在组件中使用它们。但是,我想知道是否有更好的解决方案,例如使用 Input、Output、EventEmitter 或 Subject。

message.component.html

<div *ngIf="isTodosLoaded && !appService.isAPIError">{{ todos.title }}</div>
<div *ngIf="!isTodosLoaded && appService.isAPIError">{{ appService.APIErrorMessage }}</div>

message2.component.html

<div *ngIf="isTodos2Loaded && !appService.isAPI2Error">{{ todos2.title }}</div>
<div *ngIf="!isTodos2Loaded && appService.isAPI2Error && !appService.isAPIError">{{ appService.APIErrorMessage }}</div>

message.component.ts

export class MessageComponent implements OnInit {
  isTodosLoaded = false;
  todos;

  constructor(private messageService: MessageService,
  private appService: AppService) { }

  ngOnInit() {
    this.messageService.getData()
      .subscribe(
        (response) => {
          this.todos = response;
          this.isTodosLoaded = true;
        },
        (error) => {
          this.appService.isAPIError = true;
        }
      )
  }
}

message.component.ts

export class Message2Component implements OnInit {
  isTodos2Loaded = false;
  todos2;

  constructor(private message2Service: Message2Service,
  private appService: AppService) { }

  ngOnInit() {
    this.message2Service.getData()
      .subscribe(
        (response) => {
          this.todos2 = response;
          this.isTodos2Loaded = true;
        },
        (error) => {
          this.appService.isAPI2Error = true;
        }
      )
  }
}

app.service.ts

export class AppService {
  public isAPIError = false;
  public isAPI2Error = false;
  public APIErrorMessage = "API Failure"

  constructor() { }
}

源码:https://stackblitz.com/edit/angular-pwwicc

【问题讨论】:

  • 看起来这些服务的行为方式并没有太大的不同。你不能用一个可以用适当的参数调用两次的服务来替换它吗?
  • 这是一个更大项目的简化版本。我们在每个组件中都有一个服务,它们还有其他定义。
  • 看看我为管理这种场景而编写的库,ngx-rxcache medium.com/@adrianbrand/…

标签: javascript html angular typescript observable


【解决方案1】:

有多种方法可以实现:

  • 获取父节点中的数据并通过 Input 发送给子节点。

  • 在应用程序的某处获取数据并将其保存在服务中(在主题或变量中),然后从服务中获取您孩子的数据。

  • 使用ngrx 在组件之间共享状态。

第二个例子:

在父级中:

fetch(...).subscribe(result => this.myService.setResult(result))

为您服务:

result = new BehaviorSubject(null)

setResult(result):void{
  this.result.next(result);
}

在您的子组件中:

this.myService.result.subscribe(result => {...})

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 2017-05-11
    • 2021-01-15
    • 2020-02-05
    • 1970-01-01
    相关资源
    最近更新 更多