Angular項目Auth Service
ng g s services/auth
1,領域對象中增加Auth對象。
基于token的認證。
import { User } from './user.model'; import { Err } from './error.model'; export interface Auth { user?: User; userId?: string; err?: string; token?: string; }
2,注冊
返回Auth對象。
如果用戶已經存在就拋出錯誤。
//注冊 register(user: User): Observable<Auth> { const uri = `${this.config.uri}/${this.domain}`; return this.httpClient .get(uri, { params: { 'email': user.email } }) .pipe( switchMap(res => { if ((<User[]>res).length > 0) { return throwError('username existed'); } return this.httpClient .post(uri, JSON.stringify(user), { headers: this.headers }) .pipe(map(r => ({ token: this.token, user: <User>r }))); }) ) }
3,登錄
返回Auth對象。
//登錄 login(username: string, password: string): Observable<Auth> { const uri = `${this.config.uri}/${this.domain}`; return this.httpClient.get(uri, { params: { 'email': username, 'password': password } } ) .pipe( map(res => { const users = <User[]>res; if (users.length === 0) { throw new Error('Username or password incorrect'); } return { token: this.token, user: users[0] } })) }