首页 文章

如何在路由中将值从父组件传递给子组:Angular 2

提问于
浏览
2

我有一个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;
    }   
}
....
....

所以,现在我的浏览器输出如下:

enter image description here

现在我想传递这个值1或0,我点击按钮到Child组件,我想用“child works”行显示它,如下所示:

enter image description here

单击按钮时,两个值都应该更改 . 我试图使用服务但不工作 . 我不想在URL中附加val并将路径作为路由参数发送,因为它将在url中可见 .

3 回答

  • 0

    有两种方法可以正确提供服务,我不记得确切的名称:

    • 一个全局服务,您在模块中定义,可以在模块内声明的所有组件内访问:
    @NgModule({
        ...
        providers: [yourServiceName]
    })
    
    • 本地服务,我想,它被称为专用服务 . 你在组件内提供什么
    @Component({
        ...
        providers: [yourService]
    })
    

    此组件以及此组件的所有子组件都可以访问此服务 .

    如果您正在执行这两项中的任何一项,那么数据应该在您所需的组件中可用 .

    切记不要在两个组件中提供服务 . 它应该在更高的层次结构中提供 .

  • 1

    您还可以在构造函数中将父组件注入到子组件中:

    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();
     }
    }
    
  • 0

    您需要在模块级而不是组件级提供服务 . 请查看以下代码:

    你的模块:

    @NgModule({
    imports: [BrowserModule,
              HttpModule
             ],
    declarations: [App],
    providers: [SharedService],
    bootstrap: [App]
    })
    export class AppModule { }
    

    你的服务:

    export class SharedService {
       public val: any = 0;
    }
    

    你的app组件:

    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 将只创建一个实例 .

    希望能帮助到你!!

相关问题