Angular 调用服务逻辑
1,proejcts初始化赋值不需要了。
projects = [ { id: 1, name: "企业协作平台", desc: "这是一个企业内部项目", coverImg: "assets/images/covers/0.jpg" }, { id: 2, name: "自动化测试项目", desc: "这是一个企业内部项目", coverImg: "assets/images/covers/1.jpg" } ];
在构造函数中赋值。
constructor(private dialog: MatDialog, private cd: ChangeDetectorRef, private projectService: ProjectService) { this.projectService.get("37489e0c-df34-c261-71c4-ce75357e3035").subscribe(projects => this.projects = projects); }
2,装loadsh
npm i --save loadash
npm i --save-dev @types/lodash
private getThumbnails() { return _.range(0, 40).map(i => `/assets/img/covers/${i}_tn.jpg`); }
3, 初始projects为空的问题。
脏值检测
this.projectService.get("37489e0c-df34-c261-71c4-ce75357e3035").subscribe( projects => { this.projects = projects; this.cd.markForCheck(); } );
4,用filter代替 if (!project) return;
dialogRef.afterClosed().subscribe((project) => { if (!project) return; this.projectService.add(project); this.cd.markForCheck(); });
用filter代替
dialogRef.afterClosed().pipe(filter(n => n)).subscribe((project) => { this.projectService.add(project); this.cd.markForCheck(); });
5, subscribe()中返回的还是一个流,
this.projectService.add(project);返回还是流
我们不做subscribe()中的subscribe()。两个流就应该可以合并。
switchMap中调用service,返回的还是一个流,所以要拍扁。
dialogRef.afterClosed() .pipe( filter(n => n), switchMap(v => this.projectService.add(v))) .subscribe(project => console.log(project));
6,保存后返回的是缩略图,把缩略图转成大图。
Object coverImg: "/assets/images/covers/9_tn.jpg" desc: "aa" id: "Kd27aid" name: "test"
dialogRef.afterClosed() .pipe( filter(n => n), map(val => ({ ...val, coverImg: this.buildImgSrc(val.coverImg) })), switchMap(v => this.projectService.add(v))) .subscribe(project => console.log(project)); private buildImgSrc(img: string): string { return img.indexOf('_') > -1 ? img.split('_')[0] + '.jpg' : img; }
7, 怎样unsubscribe?用take(1)代替unsubscribe()。节省unsubscribe。
不管是保存,还是关闭只需要take(1)一次。
dialogRef.afterClosed() .pipe( take(1), filter(n => n), map(val => ({ ...val, coverImg: this.buildImgSrc(val.coverImg) })), switchMap(v => this.projectService.add(v))) .subscribe(project => { this.projects = [...this.projects, project]; this.cd.markForCheck(); });
8,编辑project返回的结果在前端处理
const index = this.projects.map(p => p.id).indexOf(project.id); this.projects = [...this.projects.slice(0, index), project, ...this.projects.slice(index + 1)];
9,在ngOnDestory中取消订阅
constructor(private dialog: MatDialog, private cd: ChangeDetectorRef, private projectService: ProjectService) { this.sub = this.projectService.get("37489e0c-df34-c261-71c4-ce75357e3035").subscribe( projects => { this.projects = projects; this.cd.markForCheck(); } ); } ngOnDestroy(): void { if (this.sub) { this.sub.unsubscribe(); } }
如果觉得本文对您有帮助~可以
微信支持一下: