我有一个app.component和child.component。我想传递我在路由器插座中传递的子组件内的变量。
路由在app.module.ts中显示如下:
const routes: Routes = [
{'path': '', 'component': ChildComponent}
]
app.component.html:
<button (click) = "toggle()">toggle</button>
<p>toggle value in app.component.html :</p> {{val}}
<router-outlet></router-outlet>
app.component.ts:
....
....
val = 1;
toggle(){
if(this.val == 1){
this.val = 0;
}else{
this.val = 1;
}
}
....
....
所以,现在我的浏览器输出如下:
现在我想传递这个值1或0,我点击按钮到Child组件,我想用&#34;子作品&#34;像这样的行:
单击按钮时,两个值都应该更改。我试图使用服务但不工作。我不想在网址中附加val并将路径作为路径参数发送,因为它会在网址中显示。
答案 0 :(得分:1)
有两种方法可以正确提供服务,我不记得确切的名称:
您在模块中定义的全局服务,可以在模块内声明的所有组件内访问:
@NgModule({
...
providers: [yourServiceName]
})
本地服务,我猜,它被称为专用服务。你在组件内提供
@Component({
...
providers: [yourService]
})
此组件以及此组件的所有子组件都可以访问此服务。
如果您正在执行这两项中的任何一项,那么数据应该在您所需的组件中可用。
请记住,不要在两个组件中提供服务。它应该以更高的层次结构提供。
答案 1 :(得分:0)
您还可以在构造函数中将父组件注入到子组件中:
export class ChildComponent {
constructor(private app: AppComponent) {...}
}
这是一种传递事件的方式,作为问题的作者,但我不建议采用这种方式(只有在有充分理由说明为什么要与父母和孩子结合)
@Component({
selector: 'my-app',
template: `
<button (click)="toggle()">click</button>
<child-component></child-component>
`,
})
export class App {
subject = new Subject();
id=0;
toggle() {
this.subject.next(this.id++);
}
}
@Component({
selector: 'child-component',
template: `
{{id | async }}
`,
})
export class Child {
id;
constructor(private app: App) {
this.id = app.subject.asObservable();
}
}
答案 2 :(得分:0)
您需要在模块级别而不是组件级别提供服务。请参阅以下代码:
你的模块:
@NgModule({
imports: [BrowserModule,
HttpModule
],
declarations: [App],
providers: [SharedService],
bootstrap: [App]
})
export class AppModule { }
您的服务:
export class SharedService {
public val: any = 0;
}
你的应用组件:
constructor(private sharedService: SharedService){
}
....
....
this.sharedService.val = 1;
toggle(){
if(this.sharedService.val == 1){
this.sharedService.val = 0;
}else{
this.sharedService.val = 1;
}
}
....
....
在上面的组件中,不要提供 SharedService 作为提供者,否则它将创建SharedService的新实例。
在模块级别使用 SharedService 只会创建一个实例。
希望它有所帮助!!