Heim  >  Fragen und Antworten  >  Hauptteil

Interaktion zwischen ngAfterViewInit und Observable im Angular-Lebenszyklus

<p><strong>enable.service.ts</strong></p> <pre class="brush:php;toolbar:false;">@Injectable({ bereitgestelltIn: 'root' }) Exportklasse EnableService { isEnabled$ = from(this.client.init()).pipe( switchMap(() => this.client.getEnabled()), map(([enabled, isAdmin]) => ({enabled: true, isAdmin: false})), Aktie() ); // 不完全是这样, 但是是一种返回enable und isAdmin的observable Konstrukteur( // 一些构造函数 ) {} }</pre> <p><strong>main.component.ts</strong></p> <pre class="brush:php;toolbar:false;">export class MainComponent implementiert OnInit, AfterViewInit, OnDestroy { @ViewChild('mymap') containerRef: ElementRef<HTMLDivElement>; isAdmin: boolean = false; isEnable: boolean = false; Konstrukteur( privater enableService: EnableService, ) { this.enableService.isEnabled$.subscribe(res => {this.enable = res.enabled; this.isAdmin = res.isAdmin}); } async ngAfterViewInit(): Promise<void> { // HACK: Ermöglicht den Zugriff auf „enableService“, um die ContainerRef-Funktion #mymap zu verwenden Warten auf neues Versprechen(resolve => setTimeout(resolve, 1000)); // 必须存在才能正确隐藏/移除地图 if (this.containerRef) { // 一些第三方方sdk初始化只有在containerRef存在时才执行 } }</pre> <p><strong>main.component.html</strong></p> <pre class="brush:php;toolbar:false;"><div #mymap *ngIf="!isEnable || isAdmin"></div></pre> <p> ,它将会出错。</p> <p>有没有办法确保ngAfterViewInit在enableService获取值之后执行?</p> <p>为true, 会导致问题, 同样, 如果它一开始就是true,最终还是true,也会导致错误.我尝试将observable的订阅从构造函数移到ngOnInit中,也不起作用.</p>
P粉131455722P粉131455722404 Tage vor435

Antworte allen(1)Ich werde antworten

  • P粉026665919

    P粉0266659192023-08-17 09:14:04

    试试这个有用吗?

    ts

    get isEnabled$() {
        return this.enableService.isEnabled$;
    }

    html

    <div #mymap *ngIf="!(isEnabled$ | async).isEnable || (isEnabled$ | async).isAdmin"></div>

    Antwort
    0
  • StornierenAntwort