M
M
Maxim Melnikov2019-05-08 12:10:13
Angular
Maxim Melnikov, 2019-05-08 12:10:13

Angular 5 use of static data in layout?

Hello everyone, I have routes

path: '',
        component: AppLayoutComponent,
        children: [
            { path: '', component: ProgramsComponent, canActivate: [AuthGuard], data: { display: 'main_page' } },
            { path: 'profile', component: AccountProfileComponent, canActivate: [AuthGuard], data: { display: 'profile' } },
            { path: 'promocode', component: AccountPromocodeComponent, canActivate: [AuthGuard], data: { display: 'program' } },
        ]

each page has a component that is subscribed to data.display and everything works, but due to optimization, this component was moved to AppLayoutComponent and it stopped seeing data.display, how can this be resolved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Melnikov, 2019-05-08
@MrPhelko

I decided this way, suddenly someone needs it
Wrote DataDisplayService which is subscribed to the page change event of the Route
when changing the display parameter, I call the event
turned out even better than it was
here is an example:

import { Injectable } from '@angular/core';
import { Router, NavigationEnd, PRIMARY_OUTLET } from '@angular/router';
import { Subscription, Subject } from 'rxjs';
import { filter, map, flatMap } from 'rxjs/operators';



@Injectable()
export class DataDisplayService {

    sub: Subscription;
    display: string;

    private displaySubject = new Subject<string>();
    displayOb = this.displaySubject.asObservable();

    constructor(private router: Router) {
        this.sub = this.router.events.pipe(
            filter(event => event instanceof NavigationEnd),
            map(_ => this.router.routerState.root),
            map(route => {
                while (route.firstChild)
                    route = route.firstChild;

                return route;
            }),
            flatMap(route => route.data))
            .subscribe(data => {
                let display = data['display'];

                if (this.display !== display) {
                    this.display = display;
                    this.displaySubject.next(display);
                }
            });
    }

}

and in need components just subscribed

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question