i have an service to change the title of Action bar Dynamic but when i tap the back button on android it stays with the new title instead of the old title when i get back: eg: Product > Detail. When i hit back its stay Detail instead of Product again; What im missing here ??
service.ts
import { Injectable, OnInit } from "@angular/core";
import { BehaviorSubject, Observable } from "rxjs/index";
@Injectable()
export class ActionBarService implements OnInit {
// tslint:disable-next-line: ban-types
private title = new BehaviorSubject<String>("ActionBar");
private title$ = this.title.asObservable();
constructor() {}
ngOnInit() {
this.getTitle();
}
// tslint:disable-next-line: ban-types
setTitle(title: String) {
this.title.next(title);
}
// tslint:disable-next-line: ban-types
getTitle(): Observable<String> {
return this.title$;
}
}
Action bar xml
<!--ACTION BAR-->
<ActionBar class="action-bar roboto-regular">
<NavigationButton icon="res://menu" (tap)="openDrawer()" *ngIf="title !== 'Detail' " ></NavigationButton>
<NavigationButton icon="res://back" (tap)="goBack()" *ngIf="title === 'Product ' " ></NavigationButton>
<ActionItem ios.systemIcon="2" icon="res://shopping_black" ios.position="right"></ActionItem>
<StackLayout orientation="horizontal"
<Label class="action-bar-title" text="{{title}}" padding="10"></Label>
</StackLayout>
</ActionBar>
<!--ACTION BAR-->
Actionbar.ts
import { Component, OnInit } from "@angular/core";
import { ActionBarService } from "../shared/action-bar-title";
@Component({
selector: "actionbar-place",
moduleId: module.id,
templateUrl: "./actionbar.component.html",
styleUrls: ["./actionbar.css"]
})
export class MarketPlaceComponent implements OnInit {
title: any;
constructor(private actionBarTitle: ActionBarService) {
}
ngOnInit() {
this.actionBarTitle.getTitle().subscribe((appTitle) => {
this.title = appTitle;
});
}
Product and Detail page.ts
ngOnInit() {
this.actionBarTitle.setTitle("My Title");
}
It's purely expected, you have one instance of service (I believe you have it injected in the module / root), which has only one instance of title$ (Observable) whose value is changed on every ngOnInit
.
So when you navigate from Product to Detail, ngOnInit
triggered on Detail component will update the Observable with the Detail title, at same time the ActionBar in the previous component (Product) is also listening to the changes and will update it's own title too.
I see this as a overhead, to use Service to update ActionBar title. You may simply expose @Input from ActionBar and set the title every time when you put it in a component. Or if you still prefer to use a Service, then mark that as a Provider at component level, so every component will have it's own instance therefore won't interferer with other components.