我正在尝试将我的JSON数组对象从服务器映射到角度模型。我相信最好的方法就是尽快将它们放入地图管道中。不确定如何使用地图运算符来完成此操作。
稍后,我将使用复杂的数据源流程来填充表格并进行分页。我看不到如何从服务器初始获取此后分解json。
我尝试使用类和构造函数。我尝试创建另一个采用该特定模型列表的类。而且我尝试在类上使用可反序列化的方法。我相信必须有一种角度的魔术方法可以做到这一点。有任何想法吗?
p.s对于反应式编程来说还是新手!
export class PlaylistService {
constructor(private http: HttpClient) { }
findPlaylistTracks(
playlistId: string, filter = '', sortOrder = 'asc',
pageNumber = 0, pageSize = 3): Observable<PlaylistItem[]> {
return this.http.get<PlaylistItem[]>('api/spotify/playlist- item',{
params: new HttpParams()
.set('playlistId', playlistId.toString())
.set('filter', filter)
.set('sortOrder', sortOrder)
.set('pageNumber', pageNumber.toString())
.set('pageSize', pageSize.toString())
})
.pipe(
map((res: PlaylistItem[]) => <PlaylistItem[]>res['payload']),
tap( val => console.log('are they mapped to models ?',val)));
}
}
export interface PlaylistItem {
albumInfo: PlayListAlbum;
artists: PlayListArtist;
playlistName: string;
trackNumber: number;
trackDuration: string;
trackUri: string;
}
export interface PlayListArtist{
artistName: string;
fullArtistInfo: string;
}
export interface PlayListAlbum{
albumName: string;
relatedAlbums: string;
}
{playlist_name: "Dubliners", track_name: "Seven Drunken Nights - 1993
Remaster", album_info: {…}, artists: {…}, track_duration: "3:46", …}
{playlist_name: "Dubliners", track_name: "The Black Velvet Band",
album_info: {…}, artists: {…}, track_duration: "3:36", …}
{playlist_name: "Dubliners", track_name: "The Foggy Dew", album_info:
{…}, artists: {…}, track_duration: "3:42", …}
没有错误。 tap()日志中的val仍会打印json键/值。
答案 0 :(得分:1)
这是我最后所做的:
创建了此界面。
export interface Deserializable {
deserialize(input: any): this;
}
将其添加到我的课程中
export class PlaylistItem implements Deserializable {
public album_info: PlayListAlbum;
public artists: PlayListArtist;
public playlist_name: string;
public track_number: number;
public track_duration: string;
public track_uri: string;
public track_name: string;
deserialize(input: any) {
Object.assign(this, input);
this.album_info = new PlayListAlbum().deserialize(input.album_info);
this.artists = new PlayListArtist().deserialize(input.artists);
return this;
}
}
export class PlayListAlbum implements Deserializable {
public album_name: string;
public related_albums: string;
deserialize(input: any): this {
return Object.assign(this, input);
}
}
export class PlayListArtist implements Deserializable {
public artist_name: string;
public full_artist_info: string;
deserialize(input: any): this {
return Object.assign(this, input);
}
}
然后在Pipe()-> Map()中进行转换,如下所示:
}).pipe(
map(res => res['payload'].map(data => new PlaylistItem().deserialize(data)))
);
}
我必须使用像json这样的蛇形保护套。但这有效。现在我有了角度模型。