建立领域对象并在domain中建立一个index.ts用于组织文件。在index.ts中导出所有的领域对象。
1,新建project.service,加add方法。
import { Project } from './../domain'; import { HttpClient } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class ProjectService { private readonly domain = 'projects'; private headers = new Headers({ 'Content-type': 'application/json' }); constructor(private httpClient: HttpClient, @Inject('BASE_CONFIG') private config: any) { } //POST add(project: Project) { project.id = undefined; const uri = `${this.config.uri}/${this.domain}`; return this.httpClient.post(uri, JSON.stringify(project)).pipe( map(res => res as Project) ) } }
2,加更新方法
PUT会全部更新,patch只更新部分属性。不要图方便去做方法范围之外的更新。用一个toUpdate指定只更新这3个属性。
//PUT/patch update(project: Project): Observable<Project> { const uri = `${this.config.uri}/${this.domain}/${project.id}`; const toUpdate = { name: project.name, desc: project.desc, coverImg: project.coverImg } return this.httpClient.patch(uri, JSON.stringify(toUpdate)).pipe( map(res => res as Project) ) }
3,删除
project是一个顶级元素,级联删除。删除一个project需要删除Project,project关联的所有列表task-list和列表下面的所有任务task。
json-server会级联删除,所以我们删除列表和它下面的tasks。
从taskLists数组中得到Observable流。
//DELETE delete(project: Project): Observable<Project> { const delTasks$ = from(project.taskLists ? project.taskLists : []).pipe( mergeMap(listId => this.httpClient.delete(`${this.config.uri}/taskLists/${listId}`)), count() ); const uri = `${this.config.uri}/${this.domain}/${project.id}`; return delTasks$.pipe( switchMap(_ => this.httpClient.delete(uri).pipe( mapTo(project) )) ) }
4,get
//GET get(userId: string): Observable<Project[]> { const uri = `${this.config.uri}/${this.domain}`; return this.httpClient.get(uri, { params: { 'members_like': userId } }).pipe( map(res => res as Project[]) ) }