Angular項目Project Service
建立領域對象并在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[]) ) }
如果覺得本文對您有幫助~可以微信支持一下:




浙公網安備 33010602011771號