Angular中HTTP GET请求后如何仅修改对象的单个属性
解决方案
1. 调整类型定义,兼容双场景
先定义接口描述后端返回的author对象结构:
interface Author { id: number; // 可根据后端实际返回补充其他属性,比如name等 }
修改Article类的author属性为联合类型,同时在构造函数里自动完成对象转ID的转换,这样既适配POST提交时的number类型ID,也兼容GET返回的Author对象:
import moment from 'moment'; import { Moment } from 'moment'; interface Author { id: number; } export class Article { id: number; author: number | Author; title: string; content: string; date: Moment; readingTime: number; draft: boolean; constructor(obj: Partial<Article>) { Object.assign(this, obj); this.date = moment(this.date); // 自动将author对象转为ID if (typeof this.author === 'object' && this.author !== null) { this.author = this.author.id; } } }
2. 修正updateArticle方法的类型问题
如果不想修改Article类的类型,也可以在数据处理时用类型断言明确author的对象类型,同时注意map会返回新数组,需重新赋值:
updateArticle(): void { this.register(this.articleService.getArticles() .pipe( tap(articles => { const processedArticles = articles.map(article => { // 类型断言告知TS当前author是对象类型 const typedArticle = article as Omit<Article, 'author'> & { author: Author }; if (typeof typedArticle.author === 'object' && typedArticle.author !== null) { return { ...typedArticle, author: typedArticle.author.id } as Article; } return article; }); this.articles = processedArticles; }) ) .subscribe()); }
3. POST请求提交处理
经过上述处理后,Article实例的author已统一为number类型,提交时直接传入article.author即可,无需额外转换。
内容的提问来源于stack exchange,提问作者fnyve
相关产品推荐
相关产品推荐

