角。如何根据服务的操作切换组件

假设我有 2 个组件,aComponent并且bComponent. 我把它们重新放在里面AppComponent


<app-a>

<app-b>

而且我有myService有方法的服务.trigger()。


我想要的是仅显示aComponent,但每当我myService.trigger()从另一部分代码调用时,它就会切换并显示bComponent。这是我无法达到的完美实现。


问题是:有可能这样做吗?如果不是什么是最好的最接近的解决方案。


我得到的唯一可行的解决方案:


我.trigger()在里面加了AppComponent


export class AppComponent {

  title = 'spa';

  show: boolean = false;

  trigger() {

    this.show = true;

  }

}

并像这样渲染组件:


<div *ngIf="!show; else show">

  <app-a></app-a>

</div>


<ng-template #show>

  <app-b></app-b>

</ng-template>

然后每当我想触发切换时,我将应用程序的实例添加到构造函数并调用它的方法:


export class AnotherComponent implements OnInit {

  constructor(

    private app: AppComponent

  ) {}


  ngOnInit(): void {

    this.app.trigger();

  }

}

即使它工作得很好,我自己也看到这是一个肮脏的解决方案。组件不打算在另一个组件内部使用,但服务是。


哆啦的时光机
浏览 90回答 2
2回答

慕妹3242003

你可以Subject从rxjs图书馆使用。在您的服务文件中:// a-service.service.tsimport { Injectable } from '@angular/core';import { Subject } from 'rxjs';@Injectable({ providedIn: 'root' })export class AService {&nbsp; &nbsp; private subject = new Subject<any>();&nbsp; &nbsp; trigger(state: boolean) {&nbsp; &nbsp; &nbsp; &nbsp; this.subject.next(state);&nbsp; &nbsp; }&nbsp; &nbsp; getTrigger(): Subject<any> {&nbsp; &nbsp; &nbsp; &nbsp; return this.subject;&nbsp; &nbsp; }}在你的AppComponent:// app.component.ts...private show = false;constructor (private aService: AService) { }ngOnInit() {&nbsp; &nbsp; this.aService.getTrigger().subscribe(state => {&nbsp; &nbsp; &nbsp; &nbsp; this.show = state;&nbsp; &nbsp; });}模板可以是您提供的 - 很好:<div *ngIf="!show; else show">&nbsp; <app-a></app-a></div><ng-template #show>&nbsp; <app-b></app-b></ng-template>如果你想从另一个组件触发,你可以这样做:// another.component.ts...&nbsp; &nbsp;&nbsp;constructor (private aService: AService) { }ngOnInit() {&nbsp; &nbsp; this.aService.trigger(true);}

SMILET

在不直接相关的不同组件和服务之间进行通信的一种方法是通过“主题”。您可以尝试创建一个主题并将值从myService.trigger().&nbsp;subject您可以从要访问该触发器数据的任何组件订阅它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript