在Injectable上添加代理

huangapple go评论70阅读模式
英文:

Add proxy on Injectable

问题

我有一个AngularTS前端,有一个名为SaveService的服务。

我想在它上面添加一个代理。我没有找到很多关于它的文档。
我尝试了一个简单的实现:

export class SaveService {
  private proxyService: SaveService | null = null;

  constructor(private injector: Injector) {
    const originalService = this.injector.get(SaveService);
    const proxyService = new Proxy<SaveService>(originalService, {
      get: (target, prop: keyof SaveService, receiver) => {
        console.log(`Calling method: ${prop}`);
        return target[prop];
      },
    });

  }
}

但是它不能像这样工作,因为this.injector.get(SaveService)是一个循环依赖

有没有办法在这个可注入的服务上添加代理?

英文:

I have a AngularTS front-end, with a service SaveService

I would like to add a Proxy on it. I did not find a lot of documentation about it.
I tried naive implementation :

export class SaveService {
  private proxyService: SaveService | null = null;

  constructor(private injector: Injector) {
    const originalService = this.injector.get(SaveService);
    const proxyService = new Proxy<SaveService>(originalService, {
      get: (target, prop: keyof SaveService, receiver) => {
        console.log(`Calling method: ${prop}`);
        return target[prop];
      },
    });

  }
}

But it cannot works like this because this.injector.get(SaveService) is a Circular dependency

Any ways to add a proxy on this injectable service ?

答案1

得分: 0

我明白你在说使用代理时的意思,但在 Angular 中,这通常被称为 拦截器。它的工作是拦截请求并对其进行一些处理,通常是附加一些标头或记录日志。

@Injectable()
export class InterceptorService implements HttpInterceptor {
  public intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    console.log('请求:', req),
    return next.handle(req).pipe(
      tap((res: HttpResponse<any>) => console.log('响应:', res)),
    );
  }
}

在你的情况下,它可能看起来像这样:

@Injectable()
export class InterceptorService implements HttpInterceptor {
  // 假设这是你的 auth 服务的名称
  constructor(private firebaseService: FirebaseService)

  public intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // 检查用户是否已经认证
    if (firebaseService.isAuthenticated()) {
      // 如果已认证,继续请求
      return next.handle(req);
    } else {
      // 如果未认证,进行认证并继续请求
      return firebaseService.authenticate().pipe(
        map(() => next.handle(req))
      )
    );
  }
}

因此,你的拦截器会检查用户是否已登录,如果没有,它将调用 authenticate 方法,当认证成功后,将继续原始请求。你还可以添加身份验证标头等等... 但请将此代码视为示例,并根据自己的需求进行调整。

英文:

I think I understand what you mean by using proxy, but in Angular world this would be called an Interceptor. Its job is to intercept the requests and do some stuff with them, usually to append some headers or do logging.

@Injectable()
export class InterceptorService implements HttpInterceptor {
  public intercept(
    req: HttpRequest&lt;any&gt;,
    next: HttpHandler
  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    console.log(&#39;REQUEST:&#39;, req),
    return next.handle(req).pipe(
      tap((res: HttpResponse&lt;any&gt;) =&gt; console.log(&#39;RESPONSE:)&#39;, res),
    );
  }
}

In your case, it might look like this:

@Injectable()
export class InterceptorService implements HttpInterceptor {
  // Let&#39;s pretend that&#39;s how your auth service is called
  constructor(private firebaseService: FirebaseService)

  public intercept(
    req: HttpRequest&lt;any&gt;,
    next: HttpHandler
  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    // Check if user is authenticated
    if (firebaseService.isAuthenticated()) {
      // if so, continue
      return next.handle(req);
    } else {
      // If not, authenticate and contine
      return firebaseService.authenticate().pipe(
        map(() =&gt; next.handle(req))
      )
    );
  }
}

So your interceptor check if user is logged in and if not, it'll call the authenticate method and when it's successful it continues with original request. You can also add AUTH headers and so on... But take this code as an example and adjust it to your own needs.

huangapple
  • 本文由 发表于 2023年5月28日 06:35:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定