【问题标题】:how service in angular-2 gets value dynamically in every component?angular-2 中的服务如何在每个组件中动态获取价值?
【发布时间】:2017-10-25 15:33:16
【问题描述】:

我在 angular-2 应用程序中创建了一个服务,例如:AuthService,我的应用程序中有多个组件,其中一个组件(signUpComponet)我将在注册时获取用户数据,然后我使用 AuthService 初始化什么,我想在每个组件中使用这个 AuthService。

所以我最后想调用一个服务,该服务在我初始化的每个组件中动态获取数据,以维护每个组件中的用户。

我创建了服务来使用 html 中的 window 属性存储用户的会话

我的服务

@Injectable()

export class AuthService {
Authentication(){
    var _this = this;
    _this._data = {
      user: window.data
    };
    return _this._data;
}
}

signUpComponent

export class signUpComponent{

goToSigUp(user){
//calling backend service to fetch user data as response
 this.AuthService.Signup(user).subscribe(result => {
      if(result.type == false){
        this.errMsg = result.data;
      }else{
        this.authentication = result;// when data successfully retrieves call AuthService to store user as a window session and use in it this service in every component?   
      }   

    });
}
}

我希望这一点很清楚,我不知道当用户作为回调到达时如何调用该服务,因为我正在学习 Angular。

【问题讨论】:

  • 1) 在您的根模块(应用程序)中提供服务。 2)在该服务中创建一个字段。 3) 随时更新该字段

标签: angular angular-services


【解决方案1】:

您需要在 app.module 中将您的服务设置为提供者

@NgModule({
imports: [BrowserModule,
    HttpModule,
],
declarations: [AppComponent,

],
providers: [AuthService],
bootstrap: [AppComponent]

}) 导出类 AppModule { }

现在设置 this.authentication 将可以在任何地方访问。

希望对你有帮助!!

【讨论】:

    猜你喜欢
    • 2020-02-14
    • 2017-10-06
    • 2017-10-18
    • 2022-09-27
    • 2020-01-03
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    相关资源
    最近更新 更多