【发布时间】: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() { }
}
【问题讨论】:
-
看起来这些服务的行为方式并没有太大的不同。你不能用一个可以用适当的参数调用两次的服务来替换它吗?
-
这是一个更大项目的简化版本。我们在每个组件中都有一个服务,它们还有其他定义。
-
看看我为管理这种场景而编写的库,ngx-rxcache medium.com/@adrianbrand/…
标签: javascript html angular typescript observable