angular - Getting multiple items out of this.router.events.subscribe() -
i subscribing on router events change title of page when routes change, so
this.routersub$ = this.router.events .filter(event => event instanceof navigationend) .map(() => this.activatedroute) .map(route => { while (route.firstchild) route = route.firstchild; return route; }) .filter(route => route.outlet === 'primary') .mergemap(route => route.data) .subscribe((event) => { title = event['title'] ? `${event['title']}` : 'default title' this.title.settitle(title); });
my issue on scenarios, want set title value in url (part of route). how do here? know cannot subscribe url events having hard time figuring out map inside.
here trying failing
this.router.events .filter(event => event instanceof navigationend) .map(() => { return this.activatedroute }) .switchmap(route => { return route.data.combinelatest(route.url, (data, url) => { return data['title'] ? `title: ${data['title']}` : url.join(''); }); })
on .switchmap line, route of type activatedroute, route.data of type object , error on combinelatest() line is
route.data.combinelatest not function
if leave aside angular routing details, want combine values 2 different streams. there's @ least couple of ways how that.
case 1. want update title whenever either of streams emits , use recent values both.
use combinelatest
:
const gettitle$ = (activatedroute) => { return activatedroute.url .combinelatest(activatedroute.data, (url, data) => { return url + data; }); }; const url = rx.observable.interval(400).take(3).map(x => `url_${x} `); const data = rx.observable.interval(200).take(6).map(x => `data_${x}`); gettitle$({ url, data }).subscribe(title => console.log(title));
<script src="https://unpkg.com/@reactivex/rxjs@5.0.3/dist/global/rx.js"></script>
case 2. want update title when url
stream emits, recent value data
stream.
use withlatestfrom
:
const gettitle$ = (activatedroute) => { return activatedroute.url .withlatestfrom(activatedroute.data, (url, data) => { return url + data; }); } const url = rx.observable.interval(400).take(3).map(x => `url_${x} `); const data = rx.observable.interval(200).take(6).map(x => `data_${x}`); gettitle$({ url, data }).subscribe(title => console.log(title));
<script src="https://unpkg.com/@reactivex/rxjs@5.0.3/dist/global/rx.js"></script>
if encounter observable not contain of these operators, try import them explicitly:
import 'rxjs/add/operator/combinelatest'; import 'rxjs/add/operator/withlatestfrom';
update:
to make more specific, here's code sample closer original example:
this.router.events .filter(event => event instanceof navigationend) ... // <- route mapping , filtering skipped brevity .switchmap(route => { return route.data.combinelatest(route.url, (data, url) => { // make title out of data , url return data['title'] ? `title: ${data['title']}` : url.join(''); }); }) .subscribe(title => this.title.settitle(title));
Comments
Post a Comment