[英]how to use params data in other component in angular
In my app component.在我的应用程序组件中。 I'm having components like
我有像这样的组件
app.component.html app.component.html
<app-toolbar></app-toolbar>
<app-loader></app-loader>
<router-outlet></router-outlet>
and in my app.component.ts在我的 app.component.ts
I'm subscribing data from the query params like我正在从查询参数中订阅数据,例如
this.route.queryParams.subscribe(params => {
const { statusBoolean } = params;
this.myService.status = statusBoolean;
});
here what I'm trying is I'm having a button in my toolbar.我在这里尝试的是我的工具栏中有一个按钮。 whenever the statusBoolean is true in params then I have to display the button in the toolbar.
每当参数中的 statusBoolean 为真时,我必须在工具栏中显示该按钮。
in myService.ts:在 myService.ts 中:
status: boolean;
in my toolbar component:在我的工具栏组件中:
<button mat-button *ngIf="myService.status"></button>
and I tried by set and get params in service and access the params in toolbar component I'm not getting any values and also by parent-child communication nothing worked.我尝试通过设置并获取服务中的参数并访问工具栏组件中的参数我没有得到任何值,而且通过父子通信也没有任何效果。 here my toolbar component is loading first and unable to get data from service and throwing undefined.
在这里,我的工具栏组件首先加载,无法从服务中获取数据并抛出未定义。 can anyone please help me with this.
谁能帮我解决这个问题。
I did something similar, I think you can define a service bridge between your toolbar and other components:我做了类似的事情,我认为您可以在工具栏和其他组件之间定义一个服务桥:
@Injectable({
providedIn: 'root',
})
export class ToolbarService {
private toolbarComponent: ToolbarComponent = null;
public registerComponent(component: ToolbarComponent): void {
this.toolbarComponent = component;
}
public setStatus(value: boolean): void {
if (this.toolbarComponent) {
this.toolbarComponent.setStatus(value);
}
}
}
In tool bar component:在工具栏组件中:
public status: boolean = false;
public ngOnInit(): void {
this.toolbarService.registerComponent(this)
}
public setStatus(value: boolean): void {
this.status = value;
this.changeDetectorRef.detectChanges(); // I think should work without it
}
And you can use toolbarService.setStatus()
everywhere你可以在任何地方使用
toolbarService.setStatus()
You can also try a simpler solution, declare the status as observable: myService.service.ts您也可以尝试更简单的解决方案,将状态声明为可观察:myService.service.ts
@Injectable({
providedIn: 'root',
})
export class MyServiceService {
public status: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public setStatus(value: boolean): void {
this.status.next(value);
}
}
And just subscribe to value in toolbar component:只需订阅工具栏组件中的值:
public ngOnInit(): void {
this.myService.status.subscribe(status => {
this.status = status;
});
}
Do not forget to unsubscribe from subscription in ngOnDestroy不要忘记在 ngOnDestroy 中取消订阅
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.