在 Angular 中获取未结构化的对象时,可能会遇到问题。一种解决方法是使用管道(pipe)来转换我们需要的结构。
例如,我们有如下的未结构化的对象:
const unstructuredObj = {
name: 'John',
age: 25,
hobbies: ['reading', 'running'],
address: {
street: '123 Main St',
city: 'New York',
state: 'NY'
}
};
如果我们想要获取这个对象中的 name
和 hobbies
,可以使用如下的管道:
Name: {{ unstructuredObj | json | getProp:'name' }}
Hobbies: {{ unstructuredObj | json | getProp:'hobbies' | join }}
其中,json
管道将对象转换为 JSON 字符串,getProp
管道使用传入的属性名获取对象中的属性,join
管道将数组转换为字符串。需要注意的是,这里使用的 getProp
管道并不是 Angular 自带的管道,需要自己实现。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'getProp'
})
export class GetPropPipe implements PipeTransform {
transform(obj: any, propName: string): any {
return obj[propName];
}
}
以上代码中,我们创建了一个名为 getProp
的管道,通过传入对象和属性名的方式获取对象中的属性。
最后,在组件中导入 GetPropPipe
并将其声明为该组件的管道即可使用:
import { GetPropPipe } from './get-prop.pipe';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [GetPropPipe] // 在这里声明 GetPropPipe 管道
})
export class AppComponent {
unstructuredObj = {
name: 'John',
age: 25,
hobbies: ['reading', 'running'],
address: {
street: '123 Main St',
city: 'New York',
state: 'NY'
}
};
}