简体   繁体   中英

Angular 9 : How to change navbar from child component?

I want to be able to change the navbar depending on the component. My goal is to change background IMG and background height.

To do this I create a service with behaviorSubject that looks like:

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

@Injectable({
  providedIn: 'root'
})
export class DimensionService {




  private dimension = new BehaviorSubject<any>(null);
  broadCast = this.dimension.asObservable();

  constructor() { }


  updateDimension(dimension: any) {
    this.dimension.next(dimension);
  }
}

Since navbar is in app.component, I set default value in oninit like this:

dimension: any = { height: 400, img: '/assets/img/default.img' }

        ngOnInit(): void {


            this.dimensionService
                .subscribe(dim =>{this.dimension = dim});
    }

in child component I update main component like this:

dimension: any = { height: 400, img: '/assets/img/default.img' }

            ngOnInit(): void {


                this.dimensionService
                    updateDimension({height: 300, img: '/assets/img/child.png'});
        }

I want every component to have is own navbar height and background img.

In app.component.html I have this:

 <div [style.height.px]="dimension.height" [ngStyle]="{backgroundImage:'url(' + dimension.img + ')'}" style="z-index: 100; width: 100%; background-size: cover; position: relative;">... .... </div>

I implementation don't seem to be correct. I am having this error:

在此处输入图像描述

Can anyone help to handle this kind of situation?

The problem is you are changing the value of the BehaviourSubject 3 times at the same time. When your application renders, angular checks & preserves your value in its storage container to prevent variable leak (global access). So, when you created the BehaviourSubject it emitted on value which is null . While the angular is preserving this value, instantaneously, another value got emitted. That's why the error. The sol. is to remove the default configuration from the navbar & use the them as default value in the BehaviourSubject .

For a fix in your case:

dimension.service.ts

private dimension = new BehaviorSubject<any>({
  height: 400,
  img: '/assets/img/default.img'
});

navbar.component.ts

ngOnInit() {
  this.dimesionService.subscribe(dim => {
    this.dimension = dim
  });
}

child.component.ts

ngOnInit() {
  this.dimesionService.updateDimension({
    height: 300,
    img: '/assets/img/child.png'
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM