访问和更新 angular 中变量的服务 2

service to access and update the variable in angular 2

我有可变身份验证,我在应用程序根组件中像这样设置了 false

 import { Component ,Input} from '@angular/core' ;


 @Component({
 selector: 'app-root',
 templateUrl:'./app.component.html',
 styleUrls: ['./app.component.css']

})
export class AppComponent {
  authenticated = false;


}

我在angular 2 using layout中使用了组件路由 我的 html 代码是

        <app-nav-menu *ngIf="!authenticated"></app-nav-menu>

</div>

<div [ngClass]="{'campaign-process':authenticated}" >

    <app-side-menu *ngIf="authenticated"></app-side-menu>
<div [ngClass]="{'campaign-content':authenticated}">

    <app-upr-div-seach *ngIf="authenticated"></app-upr-div-seach>

    <router-outlet></router-outlet>


</div><!--campaign content-->

我想在子组件(登录组件)中更新此身份验证变量,请提供一些服务以在子组件中共享和访问它 我怎样才能做到这一点 提前致谢

已编辑 这是组件文件

  import { Component, Input } from '@angular/core';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']
})
export class LoginComponent  {





  clickedLogin(event)
  {
  console.log('here i want to update this ');

  }

 }

您可以创建一个服务来更新变量,如下所示,

@Injectable()
export class sharedService {
 authenticated :boolean;
 constructor() {
}
 Initialize() {
    this.authenticated = false;
}

 Update(input:any) {
    this.authenticated = input;
 }
}

确保注入到您的模块中,稍后您可以调用方法 Update 和 Initalize 来执行任何您需要的操作。

然后在Component1.ts

import { sharedService } from '/services/sharedService.service';
 constructor( private sharedSer : sharedService ) {

    }

Update(){
  this.sharedSer.Update(yourvalu);
}