angular - 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]);
}
解决方案
您可以在服务 project.service.ts 中定义一个新方法,并在成功登录后调用该方法以使用新端点更新 projectPath 变量。注销时将其重置为以前的值。
推荐阅读
- angular - 在角度模板中使用 Array.filter() 时获取“无法读取未定义的属性 'toUpperCase'”
- javascript - 从父节点更新孩子的道具
- python - Keras/Tensorflow:在同一个 GPU 上循环或使用 Process 训练多个模型
- powershell - 在 Windows 任务计划程序上运行 PowerShell 的问题
- php - 从 CakePHP Shell 通过 sendgrid 发送电子邮件返回响应代码 0
- python - Python需要一个类似字节的对象,而不是'str'错误
- php - Atom Beauty 找不到 PHP
- time - 日期时间颤动
- mongodb - 使用 MongoDB 命令时出错
- json - 尝试使用 jq 从 aws-cli 响应中提取值但失败了,我做错了什么?