Update view of component after value changes in service

I have a toolbar with _toolbarTitle in it which I want to update after title in my toolbar title service changes. It changes after navigating to a different page by using setToolbarTitle(). I've tried using observables but struggled to implement it correctly.

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>

Upvotes: 1

Views: 2284

Answers (1)

eko
eko

Reputation: 40647

Ok so it's probably not changing because of your OnPush ChangeDetectionStrategy.

Let's build it with observables:

service

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

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

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

component

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>

So with observables, you don't need to "get" your title because since it's a stream the async pipe in the html will continuously "observe" the changes

Upvotes: 1

Related Questions