无需使用Input()方法在Angular另一个组件中使用变量
几种无需Input()的方案获取
onlineBookingDisabledMessage 方案一:直接复用全局StartupService
你的onlineBookingDisabledMessage本来就来自StartupService的startupData,直接在目标组件里注入这个服务就能拿到数据,这是最省事的方法:
- 在目标组件中注入服务并读取数据:
import { StartupService } from '对应路径/StartupService'; @Component({ selector: '你的目标组件选择器', templateUrl: '目标组件模板.html' }) export class TargetComponent { onlineBookingDisabledMessage: string; constructor(private startupService: StartupService) { this.onlineBookingDisabledMessage = this.startupService.startupData.onlineBookingDisabledMessage; } }
- 直接在模板渲染:
<p>{{ onlineBookingDisabledMessage }}</p>
方案二:用NgRx全局状态管理适配现有架构
既然项目已经用了NgRx,把消息存入全局状态,所有组件都能订阅获取:
1. 扩展状态定义
修改根状态fromRoot.State,添加对应字段:
export interface State { // 保留原有字段 onlineBookingDisabledMessage: string; }
2. 新增Action
在BookingActions里加一个设置消息的Action:
export class SetOnlineBookingDisabledMessage implements Action { readonly type = '[Booking] Set Disabled Message'; constructor(public payload: string) {} } // 更新Action类型集合 export type BookingActions = // 原有Action | SetOnlineBookingDisabledMessage;
3. 在Reducer中处理Action
更新Reducer逻辑,存储消息到状态:
export function reducer(state: State = initialState, action: BookingActions): State { switch (action.type) { // 原有case case '[Booking] Set Disabled Message': return { ...state, onlineBookingDisabledMessage: action.payload }; default: return state; } }
4. 在原组件派发Action存状态
修改PreviusVisitStepPageComponent的构造函数,把消息存入NgRx:
constructor( private store: Store<fromRoot.State>, private startupService: StartupService, // 其他依赖 ) { // 原有代码 this.onlineBookingDisabledMessage = startupService.startupData.onlineBookingDisabledMessage; // 新增:派发送入状态 this.store.dispatch(new BookingActions.SetOnlineBookingDisabledMessage(this.onlineBookingDisabledMessage)); }
5. 目标组件订阅状态
import { Store } from '@ngrx/store'; import * as fromRoot from '对应路径/fromRoot'; @Component({ selector: '目标组件选择器', templateUrl: '目标组件模板.html' }) export class TargetComponent { // 用Observable订阅状态变化 onlineBookingDisabledMessage$ = this.store.select(state => state.onlineBookingDisabledMessage); constructor(private store: Store<fromRoot.State>) {} }
6. 模板渲染(用async管道自动订阅)
<p>{{ onlineBookingDisabledMessage$ | async }}</p>
方案三:路由参数传递(仅适用于路由跳转关联的组件)
如果两个组件是通过路由跳转的关系,可以把消息作为路由参数传过去:
- 原组件跳转时携带参数:
this.navigateService.pushRoute('目标路由地址', false, { queryParams: { disabledMsg: this.onlineBookingDisabledMessage } });
- 目标组件读取参数:
import { ActivatedRoute } from '@angular/router'; @Component({ selector: '目标组件选择器', templateUrl: '目标组件模板.html' }) export class TargetComponent implements OnInit { onlineBookingDisabledMessage: string; constructor(private route: ActivatedRoute) {} ngOnInit() { // 订阅参数变化(适用于路由复用场景) this.route.queryParams.subscribe(params => { this.onlineBookingDisabledMessage = params['disabledMsg']; }); // 若仅需首次加载,用快照读取: // this.onlineBookingDisabledMessage = this.route.snapshot.queryParams['disabledMsg']; } }
内容的提问来源于stack exchange,提问作者alex97cristian1551
相关产品推荐
相关产品推荐

