首页 > 解决方案 > 如何将变量从一个组件设置到另一个组件?

问题描述

我有两个 Angular components,一个是navbar每个页面上的一个,默认情况下navbar有一个隐藏的购物车,但是虽然有些条件是真的,但我必须显示那个购物车。

导航栏app.component在每个页面中都按原样调用:

<app-top-bar></app-top-bar> // navbar component
<router-outlet></router-outlet>

现在我有另一个component被调用NegozioComponent并作为页面路由的组件,在该组件中,我得到的条件是导航栏的购物车是否必须可见。

NegozioComponent.ts 看起来像这样

export class NegozioComponent implements OnInit {

  profilo: Profilo;
  idNegozio: string;

  constructor(private route: ActivatedRoute, private profiloService: ProfiloService) {

    this.route.params.subscribe((params: Params) => {
      this.idNegozio = params.negozio;
  });
  }

  ngOnInit(): void {
    this.profiloService.profilo(this.idNegozio).subscribe((profilo: Profilo) => {
      this.profilo = profilo;
      if(profilo.moduli) {
         // SET CART TO TRUE
       }
    });
  }

}

在它里面是 ngOnInitif(profilo.moduli)我必须将carrello变量从设置TopBarComponent为 true

TopBarComponent.ts:

import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-top-bar',
      templateUrl: './top-bar.component.html',
      styleUrls: ['./top-bar.component.scss']
    })
    export class TopBarComponent implements OnInit {
      carrello = false;
    
      constructor() { }
    
      ngOnInit(): void {
      }
    }

标签: angular

解决方案


你需要一个服务,它可以在两个组件之间传输这条信息。

您的服务:

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

@Injectable({
  providedIn: 'root',
})
export class CartService {
  public cartIsEnabled = false;

  constructor() { }

}

您的组件的 ts,其中设置了购物车的状态:

this.cartService.cartIsEnabled = true;

您的购物车组件的 html:

<cart *ngIf="cartService.cartIsEnabled"></cart>

如果未检测到更改且购物车未显示,您可以将 cartIsEnabled 变量切换为BehaviorSubject


推荐阅读