2017-04-18 69 views
0

我在其他组件(父级)内部有一个组件(子级)。这个标签叫做router-outlet。 我写了一个服务,以便孩子可以改变父母的变量,因为在这种情况下,我不能使用EventEmitterOutput,但它不起作用。没有通过Angular 2中的服务更新

服务:

import {Subject} from 'rxjs/Subject'; 

import {Injectable} from '@angular/core'; 

@Injectable() 
export class TabStatusService { 


    private sub=new Subject<boolean>(); 
    dataStatus$ = this.sub.asObservable(); 

    changeStatus(data:boolean){ 

    this.sub.next(data); 
    } 
} 

父:

@Component({ 
    ... 
    providers:[TabStatusService] 
}) 


export class SecondarytabsComponent implements OnInit { 


private status:boolean=false; 
    constructor(private tabStatusService: TabStatusService) { 


    ngOnInit() { 


    this.tabStatusService.dataStatus$.subscribe(
     data => { 
     this.status = data; 

     }); 
    } 
} 

模板:

<div> 



    <p>{{status}} </p> 


</div> 
<router-outlet></router-outlet> 

孩子:

@Component({ 
    .... 
    providers:[ConfirmationService, TabStatusService] 
}) 
export class ProceduresComponent implements OnInit { 

    constructor(private confirmationService: ConfirmationService, private tabStatusService:TabStatusService) { 


    } 

    ngOnInit() { 
    } 

    setStatus(value){ 
    this.tabStatusService.changeStatus(value); 
    } 

} 

模板:

<div> 

<button type="button" class="btn btn-primary btn-lg btn-block login-button"(click)="setStatus(true)">Back</button> 

</div> 

问题在哪里?

谢谢

+0

“不起作用”不是问题描述。你有什么努力使它工作? –

+0

我会点击子按钮,父母的“状态”变量从false更改为true。 – dstyle

+0

为什么你在每个组件上都有提供者:[TabStatusService]? – zeroflagL

回答

0

从你的孩子组成的providers元属性字段删除[TabStatusService]

当前您创建同一服务的多个实例。您需要为其提供根组件或@NgModule以共享相同的服务实例。

如果你这样做,它应该按预期工作。

+0

谢谢,现在的作品! – dstyle

+0

@dstyle很好,如果能为您解决问题,请您接受答案。谢谢。 – unitario