【问题标题】:service to access and update the variable in angular 2访问和更新角度 2 中的变量的服务
【发布时间】:2017-04-12 14:09:29
【问题描述】:

我有变量身份验证,我在应用程序根组件中设置了这样的 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 中使用布局使用了组件路由 我的 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 ');

  }

 }

【问题讨论】:

  • 你检查答案了吗?

标签: angular angular2-routing angular2-services angular2-components


【解决方案1】:

你可以做一个服务来更新变量如下,

@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);
}

【讨论】:

  • 如何在我的组件 ts 文件中添加它。你能指导我在 angular2 @Sajeetharan 上是新手吗
  • 我没有在这里更新我想更新这个变量的问题
  • 当我编写构造函数行constructor( private sharedSer : sharedService ) { } 时,它在浏览器控制台上出现错误并且组件不显示
  • 错误是 ERROR 错误:未捕获(承诺):错误:没有 SharedServiceService 的提供者!错误
  • 好的,您需要将 SharedServiceService 添加到模块内的导入中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-22
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
相关资源
最近更新 更多