angular - 如何将变量从一个组件设置到另一个组件?
问题描述
我有两个 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 {
}
}
解决方案
你需要一个服务,它可以在两个组件之间传输这条信息。
您的服务:
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。
推荐阅读
- vue.js - 在 nuxt vuex 中提交未定义
- nginx - Nginx 重写短网址
- php - 如何将会话密钥 user_id 传递给“Select from” sql 语句
- android - 部署前修改 Android App Bundle (aab) 内容
- python - 将大型应用程序 web2py 转移到新服务器
- php - 调用未定义函数 setSurroundCount() CodeIgniter 4
- java - 如何使用 Spring Data JPA 有效地处理并发创建
- c# - 当 ASP.Net 接收到带有 DateTime 属性的发布模型时,什么决定了 DateTime.Kind?
- reactjs - 有没有办法使用自己的组件类来扩展 React.Component 而无需在每个文件中导入 react?
- javascript - 我不能在 Angular 的 httpclient 结果中使用 getter 和 setter 吗?