Angular提供了一个功能强大的辅助库,叫做“rxjs/operators”。其中“map”操作符可以用来映射一个对象为另一个对象。
示例代码如下:
import { map } from 'rxjs/operators';
interface User { id: number; name: string; email: string; }
interface UserViewModel { id: number; fullName: string; emailAddress: string; }
const user: User = { id: 1, name: 'John Doe', email: 'johndoe@example.com' };
const userViewModel: UserViewModel = map((u: User) => {
return {
id: u.id,
fullName: ${u.name.first} ${u.name.last}
,
emailAddress: u.email
}
})(user);
这个例子中,我们定义了两个接口:User和UserViewModel。我们将User对象转换为UserViewModel对象,其中id和email属性的值不变,而fullName属性由User对象的name属性的first和last属性合并而成。
接着,我们使用map操作符将User对象映射成一个新的对象,这个对象遵循UserViewModel的接口规范。
最后,我们将User对象作为map操作符的参数传入,以生成映射后的UserViewModel对象。
在Angular应用程序中,你可以把这个映射放在Service、Component或Pipe里面,具体取决于你的开发需求。