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]
          }
        }))
  }

 

posted @ 2021-02-27 23:05  starof  阅读(280)  评论(0编辑  收藏  举报