简体   繁体   English

如何创建新的角度服务实例?

[英]How to create new instance of angular service?

So, I'm looking solution for the problem... Ok, let me share my thoughts and possible you could help me or say that I'm wrong.所以,我正在寻找问题的解决方案......好吧,让我分享我的想法,可能你可以帮助我或者说我错了。

Introduction:介绍:

When you are creating angular apps usually you create the service which calls like AuthService which contain methods login, logout, refreshToken and etc.当您创建角度应用程序时,通常您会创建调用 AuthService 之类的服务,其中包含登录、注销、refreshToken 等方法。

But, you also need to store somewhere your current users, it will be user who was logged in your application.但是,您还需要在某个地方存储您当前的用户,它将是登录您的应用程序的用户。 Usually you will create something like UserModel with fields like firstname, lastname, balance, group, friends and etc. And so, you are store instance of this model in AuthService.通常你会创建类似 UserModel 的东西,其中包含名字、姓氏、余额、组、朋友等字段。因此,你在 AuthService 中存储这个模型的实例。

After that for getting active user you need to inject your Auth service in your @component like this:之后,为了获得活跃用户,您需要像这样在 @component 中注入您的 Auth 服务:

constructor(private _authService: AuthService) {
  this.user = this._authservice.user;
}

Yep?是的?

The problem:问题:

So, I do not want inject authService for getting current user.所以,我不想注入 authService 来获取当前用户。 I want to have CurrentUser service which will be allowed across all modules and will contain everything about logged user like UserModel.我想要 CurrentUser 服务,该服务将在所有模块中被允许,并且将包含有关已登录用户的所有信息,例如 UserModel。

I want something like this:我想要这样的东西:

constructor(public user: UserService) {
}

BUT when user do logout I need to cleanup UserService and re-initialize every field to default value.但是当用户注销时,我需要清理 UserService 并将每个字段重新初始化为默认值。 So, this step it is a real problem.因此,这一步是一个真正的问题。 Yes, sure, I can do for... in cycle by object fields, but it's sucks.是的,当然,我可以按对象字段做 for... in cycle,但这很糟糕。 I want to create new instance of UserService and make re-assign in global scope.我想创建 UserService 的新实例并在全局范围内重新分配。

If you still do not understand - UserService was declared as provider in my root AppModule like this:如果您仍然不明白 - UserService 在我的根 AppModule 中被声明为提供者,如下所示:

@NgModule({
  imports: [
    ...
  ],
  declarations: [
    ...
  ],
  providers: [
    UserService
  ]
})
export class AppModule {}

Question: How can I create new instance for UserService and replace it in global?问题:如何为 UserService 创建新实例并在全局范围内替换它?

When user logout I want to do this and all my components will get new, clean instance of UserService without filled fields and etc. And when new user will be logged in I'll use method of UserService class like user.updateUser(data) for filling this instance.当用户注销时,我想这样做,我的所有组件都将获得新的、干净的 UserService 实例,没有填充字段等。当新用户登录时,我将使用 UserService 类的方法,如 user.updateUser(data)填充此实例。

This can be achieved by declaring the service UserService to the highest level component your user is directed to after logging in (say HomeComponent).这可以通过将服务UserService声明为您的用户在登录后被定向到的最高级别组件(例如 HomeComponent)来实现。 Continue to declare your authService as a provider in your root app.module.ts so it remains a singleton for the entire application life time.继续在您的根app.module.ts您的authService声明为提供者,以便它在整个应用程序生命周期内保持为单例。

By doing this the UserService will be created each time a User logs in and it will be available to all the children of the home component (which is why you will want to be sure to provide it at the highest level component), and it will be destroyed each time a user logs out.通过这样做,每次用户登录时都会创建UserService ,并且它将对 home 组件的所有子组件可用(这就是为什么您要确保在最高级别组件上提供它),并且它将每次用户注销时都会被销毁。 Creating a singleton for each user session.为每个用户会话创建一个单例。

@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [UserService]
})
export class HomeComponent {...}

I want to stress the highest level component.我想强调最高级别的组件。 Essentially from an Architecture perspective what you would want to do is (in this example) be sure to make the HomeComponent essentially a container component for all routes/components a logged in user would need to access thereafter.本质上,从架构的角度来看,您想要做的是(在此示例中)确保使 HomeComponent 本质上成为登录用户此后需要访问的所有路由/组件的容器组件。 Otherwise, this technique will not succeed for say sibling components, as the sharing of the UserService is dependent upon the hierarchical component structure.否则,这种技术对于同级组件将不会成功,因为UserService的共享依赖于分层组件结构。

I think the real question is why would you want this behaviour?我认为真正的问题是你为什么想要这种行为?

If it's regarding state then you should use a state management tool for this like ngrx or ng2redux so that the state is abstracted away from your components and services.如果它与状态有关,那么您应该为此使用状态管理工具,例如ngrxng2redux ,以便从您的组件和服务中抽象出状态。

Then you can cleanly logout and login with different events and handle what should happen with the states upon each action.然后你可以干净地注销和登录不同的事件,并处理每个动作的状态应该发生什么。

try to make use of BehaviorSubjects.尝试使用 BehaviorSubjects。 this should go in your service class:这应该在你的服务类中:

public userData: new BehaviorSubject({});公共用户数据:新的 BehaviorSubject({});

once you get the logged in user data, store in the behavior subject like this获得登录用户数据后,像这样存储在行为主题中

in the component:在组件中:

this.userService.userData.next(response); this.userService.userData.next(响应);

and when you need to fetch it across other components, just use this:当您需要跨其他组件获取它时,只需使用它:

this.userService.userData.value(); this.userService.userData.value();

NB: when the user refreshes, be it a service or a behavior subject, all will refresh.注意:当用户刷新时,无论是服务还是行为主体,都会刷新。 so, try using it in seasion storage or in Node cache.所以,尝试在季节存储或节点缓存中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM