如何解决循环依赖

2024-02-12

我有3项服务:

auth.service.ts、account.service.ts、http.service.ts

当用户注册时,我应该创建新帐户,因此我将 account.service.ts 导入到 auth.service.ts。我应该这样做,因为我使用注册表单数据来创建新帐户。

@Injectable()
export class AuthService {
  constructor(public accountService: AccountService) {}

  signUp(name: string, phone: string, email: string, password: string): void {

    ...

  userPool.signUp(phone, password, attributeList, null, (err: any, result: any) => {
  if (err) {

    ...

    return;
  }

  this.accountService.createAccount(name, phone, email).subscribe(res => {

    ...

    this.router.navigate(['/auth/confirmation-code']);
  });
});

}

因此,当我使用 AWS Cognito 时,我应该将授权令牌从 auth.service.ts 添加到 http.service.ts 因此我将 auth.service.ts 导入到 http.service.ts。

@Injectable()
export class HttpService {
  private actionUrl: string;
  private headers: Headers;
  private options: RequestOptions;

  constructor(
    public _http: Http,
    public authService: AuthService 
  ) {
    this.actionUrl = 'https://example.com/dev';
    this.headers = new Headers();

    this.authService.getAuthenticatedUser().getSession((err: any, session: any) => {
      if(err) return;
      this.headers.append('Authorization', session.getIdToken().getJwtToken());
    });

    this.headers.append('Content-Type', 'application/json');
    this.headers.append('Accept', 'application/json');
    this.headers.append('Access-Control-Allow-Headers', 'Content-Type, X-XSRF-TOKEN');
    this.headers.append('Access-Control-Allow-Origin', '*');

    this.options = new RequestOptions({ headers: this.headers });
  }

    get(request: string): Observable<any> {
        return this._http.get(`${this.actionUrl}${request}`)
            .map(res => this.extractData(res))
            .catch(this.handleError);
   }

在我的 account.service.ts 中,我应该使用 http.service.ts 创建新帐户。

@Injectable()
export class AccountService {
  constructor(public httpService: HttpService) {}

检测到循环依赖中的警告: src/app/core/services/account.service.ts -> src/app/core/services/http.service.ts -> src/app/core/services/auth.service.ts -> src/app/core /服务/account.service.ts

检测到循环依赖中的警告: src/app/core/services/auth.service.ts -> src/app/core/services/account.service.ts -> src/app/core/services/http.service.ts -> src/app/core /服务/auth.service.ts

检测到循环依赖中的警告: src/app/core/services/http.service.ts -> src/app/core/services/auth.service.ts -> src/app/core/services/account.service.ts -> src/app/core /services/http.service.ts

我知道这是循环依赖错误。 怎么解决呢?最佳实践? 所有服务都发挥其作用并且都很重要。


您可以使用Injector为了这。像往常一样通过构造函数注入它,然后当您需要某些导致循环依赖的服务时,从中获取该服务。

class HttpService {
  constructor(private injector: Injector) { }

  doSomething() {
    const auth = this.injector.get(AuthService);
    // use auth as usual
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何解决循环依赖 的相关文章

随机推荐