微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

服务值更改后更新组件视图

如何解决服务值更改后更新组件视图

我有一个带有 _toolbarTitle 的工具栏,我想在我的工具栏标题服务更改 title 后更新它。在使用 setToolbarTitle() 导航到不同页面后,它会发生变化。我曾尝试使用 observables,但难以正确实施。

toolbar-title.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',})
export class ToolbarTitleService {
  title: string = 'toolbarTitle';
  constructor() {}

  setToolbarTitle(title) {
    this.title = title;
  }

  getToolbarTitle() {
    return this.title;
  }
}

toolbar.component.ts

import { Component,OnInit,ChangeDetectionStrategy } from '@angular/core';
import { ToolbarTitleService } from '../services/toolbar-title.service';

@Component({
  selector: 'app-toolbar',templateUrl: './toolbar.component.html',styleUrls: ['./toolbar.component.css'],changeDetection: ChangeDetectionStrategy.OnPush,})
export class ToolbarComponent implements OnInit {
  _toolbarTitle = '';
  constructor(private toolbarTitle: ToolbarTitleService) {}

  onClick() {
    this._toolbarTitle = this.toolbarTitle.getToolbarTitle();
  }

  ngOnInit() {
    this._toolbarTitle = this.toolbarTitle.getToolbarTitle();
    console.log(this.toolbarTitle.getToolbarTitle());
  }
}

toolbar.component.html

<ion-toolbar color="primary">
  <ion-buttons slot="start">
    <ion-back-button defaultHref="/login"></ion-back-button>
  </ion-buttons>

  <ion-title> {{ _toolbarTitle }} </ion-title>

  <img src="assets/specto_logo.svg" />
</ion-toolbar>

解决方法

好的,所以它可能不会因为您的 OnPush ChangeDetectionStrategy 而改变。

让我们用 observable 来构建它:

服务

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',})
export class ToolbarTitleService {
  title = new BehaviorSubject('toolbarTitle');

  setToolbarTitle(title) {
    this.title.next(title);
  }
}

组件

export class ToolbarComponent implements OnInit {
  _toolbarTitle = this.toolbarTitle.title;
  constructor(private toolbarTitle: ToolbarTitleService) {}
//...
}

html

<ion-toolbar color="primary">
  <ion-buttons slot="start">
    <ion-back-button defaultHref="/login"></ion-back-button>
  </ion-buttons>

  <ion-title> {{ _toolbarTitle | async }} </ion-title>

  <img src="assets/specto_logo.svg" />
</ion-toolbar>

所以对于 observables,你不需要“获取”你的标题,因为它是一个流,html 中的 async 管道会不断地“观察”变化

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。