角度6

时间:2018-10-17 11:08:17

标签: angular typescript dependency-injection angular6

我在root中提供了角度服务

import {Injectable} from "@angular/core";
import {BehaviorSubject} from "rxjs";
import {Admin} from "../models/admin.model";
import {AdminsService} from "./admins.service";

@Injectable({
  providedIn: 'root'
})
export class CurrentUserService {
  public user$: BehaviorSubject<Admin> = new BehaviorSubject(null);

  constructor(private _adminsService: AdminsService) {
    console.log('current user service instantiated');
    this._adminsService.getCurrentUser()
      .subscribe(user => {
        this.user$.next(user);
      });
  }

  public update() {
    this._adminsService.getCurrentUser().subscribe(user => {
      this.user$.next(user);
    })
  }

  public clear() {
    this.user$.next(null);
  }
}

我通过以下方式在app.module中提供它和Http Interceptor:

providers: [
    CurrentUserService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
  ],

当我尝试将其注入拦截器时,我从构造函数中收到很多消息,这表明服务实例化了很多次。 任何人都可以解释这种行为,并且可能对如何解决它有所了解吗?

console with messages screenshot

1 个答案:

答案 0 :(得分:1)

这是因为您在同一模块中多次提供相同的服务-

首先由

@Injectable({
  providedIn: 'root'
})

第二次

providers: [
    CurrentUserService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
  ],

最好从第一个删除。