将登录,获取用户信息和注销的数据处理移到service层

This commit is contained in:
小海
2020-04-25 15:32:32 +08:00
parent 94b7c7e7ba
commit e397131473
3 changed files with 114 additions and 45 deletions

View File

@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { UserService } from './user.service';
describe('UserService', () => {
let service: UserService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(UserService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,96 @@
import {Injectable} from '@angular/core';
import {LoginReq, User} from '../class/User';
import {ApiService} from '../api/api.service';
import {Observable, Observer} from 'rxjs';
import {Response} from '../class/HttpReqAndResp';
import {LocalStorageService} from './local-storage.service';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private apiService: ApiService,
private localStorageService: LocalStorageService) {
}
// 存储订阅者
private userObserverArray: Observer<Response<User>>[] = [];
watchUserInfo(observer: Observer<Response<User>>) {
if (this.userObserverArray.indexOf(observer) < 0) this.userObserverArray.push(observer);
const user = this.localStorageService.getUser();
// 判断本地缓存的用户信息是否符合要求,符合要求返回本地缓存
if (this.localStorageService.isLogin() && user && !this.localStorageService.checkNeedNet()) {
observer.next(new Response<User>(user));
return {
unsubscribe() {
observer.complete();
}
}
}
// 不符合 请求网络数据并更新缓存
// 向订阅者传数据
const subscription = this.apiService.userInfo().subscribe({
next: o => {
this.localStorageService.setUser(o.result);
observer.next(o);
},
error: err => {
// console.debug('登录过期 token错误 等等');
this.localStorageService.removeToken();
observer.next(new Response<User>(null));
observer.error(err);
}
});
return {
unsubscribe() {
observer.complete();
subscription.unsubscribe()
}
}
}
login(loginReq: LoginReq, observer: Observer<Response<User>>) {
const oob = new Observable<Response<User>>(o => observer = o);
const subscription = this.apiService.login(loginReq).subscribe({
next: o => {
// 登录成功
this.localStorageService.setToken(o.result.token);
this.localStorageService.setUser(o.result);
// this.userObserver.next(o);
this.userObserverArray.forEach(ob => ob.next(o))
observer.next(o);
observer.complete();
},
error: err => {
observer.error(err);
observer.complete();
}
});
return {
unsubscribe() {
observer.complete();
subscription.unsubscribe();
}
};
}
logout(observer?: Observer<Response<string>>) {
// 如果不需要返回消息也ok
this.apiService.logout().subscribe(data => {
this.localStorageService.clear();
this.userObserverArray.forEach(ob => ob.next(new Response<User>(null)))
if (observer) {
observer.next(data);
observer.complete();
}
},
error => {
if (observer) {
observer.error(error);
observer.complete();
}
})
}
}