Angular项目User Service
1,查询用户
根据用户email的前几个字符查找用户。在添加组员,添加任务执行者的时候都会用到。
根据条件查询出用户数组。
searchUsers(filter: string): Observable<User[]> { const uri = `${this.config.uri}/${this.domain}`; return this.httpClient.get(uri, { params: { 'emails_like': filter } }).pipe( map(res => res as User[]) ) }
2,依据项目得到项目所有成员
getUsersByProject(projectId: string): Observable<User[]> { const uri = `${this.config.uri}/${this.domain}`; return this.httpClient.get(uri, { params: { 'projectId': projectId } }).pipe( map(res => res as User[]) ) }
3,处理user和project的关系,多对多
把对方的id存成数组。
添加用户项目。如果projectId已经存在,直接返回传入的user。
addProjectRef(user: User, projectId: string): Observable<User> { const uri = `${this.config.uri}/${this.domain}/${user.id}`; const projectIds = user.projectIds ? user.projectIds : []; if (projectIds.indexOf(projectId) > -1) { return of(user); } return this.httpClient.patch( uri, JSON.stringify({ projectIds: [...projectIds, projectId] }), { headers: this.headers } ).pipe( map(res => res as User) ) }
4, 删除项目。
如果projectId不存在,直接返回传入的user。
removeProjectRef(user: User, projectId: string): Observable<User> { const uri = `${this.config.uri}/${this.domain}/${user.id}`; const projectIds = user.projectIds ? user.projectIds : []; const index = projectIds.indexOf(projectId); if (index === -1) { return of(user); } const toUpdate = [...projectIds.slice(0, index), ...projectIds.slice(index + 1)] return this.httpClient.patch( uri, JSON.stringify({ projectIds: toUpdate }), { headers: this.headers } ).pipe( map(res => res as User) ) }
5,批量增加用户
在一个项目当中批量增加了多个成员,给这些成员加上projectId。
batchUpdateProjectRef(project: Project): Observable<User[]> { const projectId = <string>project.id; const memberIds: string[] = project.members ? project.members : []; return from(memberIds).pipe( switchMap(id => { //根据userId取得user信息 const uri = `${this.config.uri}/${this.domain}/${id}`; return this.httpClient.get(uri); }), filter( (user: User) => //把项目加到user中 user.projectIds ? user.projectIds.indexOf(projectId) < 0 : false ), switchMap((u: User) => this.addProjectRef(u, projectId)), reduce((users: User[], curr: User) => [...users, curr], []) ); }
如果觉得本文对您有帮助~可以
微信支持一下: