2017-04-24 98 views
2

我有一个app.component和child.component。我想通过路由器插座中传递的子组件内的变量。如何将值从父组件传递给路由中的子项:Angular 2

路由看起来像这样在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的是我得到WHN我按一下按钮,儿童成分,我想表明它“子作品”线是这样的:

enter image description here

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

+0

你可以分享你的服务代码吗?我们可以通过共享服务共享价值 –

+0

@JayakrishnanGounder我对服务感到困惑。如果你能帮助我为这种情况提供服务,那将是非常有帮助的。任何小的代码 –

+0

请找到答案 –

回答

1

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

  1. 全球性的服务,您的模块定义和可内声明的所有组件内部进行访问模块:

    @NgModule({ 
        ... 
        providers: [yourServiceName] 
    }) 
    
  2. 本地服务,我想,这就是所谓的专用service.Which你一个组件

    @Component({ 
        ... 
        providers: [yourService] 
    }) 
    
    内提供

    此组件和此组件的所有子组件都可以访问此服务。

如果你正在做这两个中的任何一个,那么数据应该在你想要的组件中可用。

切记不要在这两个组件中提供服务。它应该在更高层次上提供。

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

好这个方法,我可以在ChildComponent访问触发值,但如果我按一下按钮就不会刷新ChildComponent值。我需要在child htlm中放置另一个按钮来刷新值。如何在子html中没有新按钮的情况下刷新具有新值的子项? –

+0

或者如果我点击切换,是否有任何方法刷新子组件本身?随着该值将自动刷新。 –

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在模块级将只能创建一个实例。

希望它有帮助!

+0

我试图根据你的代码这种方法,一旦我在app.component.html点击按钮时,它正在改变两个父母和孩子的价值,但价值是没有得到儿童自动刷新我被迫换上新按钮在孩子检查改变的价值,我不想放。 –

+0

@AmanDeepSharma你应该使用[ChangeDetectorRef(https://angular.io/docs/ts/latest/api/core/index/ChangeDetectorRef-class.html)来检测变化 –

相关问题