首页 > 解决方案 > Angular,登录时更改 apiUrl

问题描述

我像这样将 apiUrl 存储在 app.config.ts 中

import {InjectionToken} from '@angular/core';

export let APP_CONFIG = new InjectionToken('app.config');

export const AppConfig: any = {
  apiUrl: 'http://localhost:3000',
};

然后我在像这样的几个服务中使用它

projectPath = AppConfig.apiUrl + '/project';
supportPath = AppConfig.apiUrl + '/support';
paymentPath = AppConfig.apiUrl + '/payment';

但是我想在用户登录时更新 apiUrl 并在注销时更新它的默认值。

如果用户登录 apiUrl 应该是

apiUrl = apiUrl + "/user"

我尝试通过对每个请求单独使用 if else 来检查。但我正在寻找更好的解决方案,因为我在很多地方都使用了 projectsPath 变量。

我的登录和注销功能

export class UserService {
  private userSubject: BehaviorSubject<User>;
  public user: Observable<User>;

  userPath = AppConfig.apiUrl + '/user';

  constructor(private router: Router,private http: HttpClient) {
    this.userSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('user')));
    this.user = this.userSubject.asObservable();
  }

  public get userValue(): User {
    return this.userSubject.value;
  }

  login(email: string, password: string) {
    return this.http.post<User>(`${this.userPath}/login`, {email, password})
      .pipe(map(user => {
        localStorage.setItem('user', JSON.stringify(user));
        this.userSubject.next(user);
        return user;
      }));
  }

  logout() {
    localStorage.removeItem('user');
    this.userSubject.next(null);
    this.router.navigate([RoutesConfig.routes.login]);
  }

标签: angular

解决方案


您可以在服务 project.service.ts 中定义一个新方法,并在成功登录后调用该方法以使用新端点更新 projectPath 变量。注销时将其重置为以前的值。


推荐阅读