Files
bbq/src/app/shared/services/business/account.service.ts
Taric Xin 9ffc4c6f89 edit
2021-12-28 10:51:44 +08:00

112 lines
3.0 KiB
TypeScript

/*
* @Author: Maple
* @Date: 2021-03-22 11:42:26
* @LastEditors: Do not edit
* @LastEditTime: 2021-05-27 11:22:02
* @Description: 全局账号服务
*/
import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { CoreService, StartupService } from '@core';
import { ReuseTabService } from '@delon/abc/reuse-tab';
import { BaseService } from '../core/base.service';
@Injectable({
providedIn: 'root',
})
export class EAAccountService extends BaseService {
// 验证码登录
public $api_login_by_captcha = `/scm/cuc/cuc/user/sms/login?_allow_anonymous=true`;
// 账号密码登录
public $api_login_by_account = `/scm/cuc/cuc/user/login?_allow_anonymous=true`;
// 退出登录
public $api_logout = `/chia/user/logout`;
constructor(public injector: Injector) {
super(injector);
}
// 注入核心服务
private get coreSrv(): CoreService {
return this.injector.get(CoreService);
}
// 注入路由
private get router(): Router {
return this.injector.get(Router);
}
// 注入路由复用服务
private get reuseTabService(): ReuseTabService {
return this.injector.get(ReuseTabService);
}
// 注入全局启动服务
private get startSrv(): StartupService {
return this.injector.get(StartupService);
}
// 登录状态
public get loginStatus(): boolean {
return this.coreSrv.loginStatus;
}
/**
* 账号密码登录
* @param username 登录账号
* @param password 登录密码
*/
loginByAccount(username: string, password: string): void {
this.asyncRequest(this.$api_login_by_account, { username, password, type: 0 }, 'POST', true, 'FORM').then((res) => {
this.doAfterLogin(res);
});
}
/**
* 短信验证码登录
* @param phone 手机号码
* @param smsCode 短信验证码
*/
loginByCaptcha(phone: string, smsCode: string): void {
this.asyncRequest(this.$api_login_by_captcha, { phone, smsCode }, 'POST', true, 'FORM').then((res) => {
this.doAfterLogin(res);
});
}
private doAfterLogin(res: any): void {
const token = res?.token;
if (token) {
// 清空路由复用信息
this.reuseTabService.clear();
// 设置用户Token信息
// TODO: Mock expired value
// res.user.expired = +new Date() + 1000 * 60 * 5;
this.coreSrv.tokenSrv.set({ token });
// 重新获取 StartupService 内容,我们始终认为应用信息一般都会受当前用户授权范围而影响
this.startSrv.load().then(() => {
let url = this.coreSrv.tokenSrv.referrer!.url || '/';
if (url.includes('/passport')) {
url = '/';
}
this.router.navigateByUrl(url);
});
}
}
/**
* 登出系统
* @param showMsg 是否显示登录过期弹窗
*/
logout(showMsg: boolean): void {
this.coreSrv.logout(showMsg);
}
/**
* 向服务器请求登出
*/
requestLogout(): void {
this.asyncRequest(this.$api_logout).finally(() => {
this.logout(false);
});
}
}