如何修改对接口的 http 响应?
how can I modify http response to a interface?
我有一个接口:
export interface Device {
id: string;
name: string
}
我用额外的数据模拟 http 响应:
import { Injectable } from '@angular/core';
import { Device } from './device.model';
import { Observable, timer } from 'rxjs';
import { mapTo } from 'rxjs/operators';
const devices = [
{
id: '1',
name: 'device1',
serial: 'fdfd'
},
{
id: '2',
name: 'device2',
serial: 'fdfd'
},
];
@Injectable({
providedIn: 'root'
})
export class DevicesDataService {
constructor() { }
getDevices(): Observable<Array<Device>> {
return timer(200).pipe(mapTo(devices));
}
}
问题是,returns 是包含 3 个字段的响应。
我怎样才能 return 一个匹配接口的响应,所以 Observable<Array<Device>>
将只包含 2 个字段?
我想调用 getDevices()
方法并使用仅具有 id、名称字段的设备对象数组进行观察。
恐怕你必须手动操作。
getDevices(): Observable<Array<Device>> {
return timer(200).pipe(mapTo(devices),
map(arr=>arr.map(({name,id})=>({name,id})));
}
我有一个接口:
export interface Device {
id: string;
name: string
}
我用额外的数据模拟 http 响应:
import { Injectable } from '@angular/core';
import { Device } from './device.model';
import { Observable, timer } from 'rxjs';
import { mapTo } from 'rxjs/operators';
const devices = [
{
id: '1',
name: 'device1',
serial: 'fdfd'
},
{
id: '2',
name: 'device2',
serial: 'fdfd'
},
];
@Injectable({
providedIn: 'root'
})
export class DevicesDataService {
constructor() { }
getDevices(): Observable<Array<Device>> {
return timer(200).pipe(mapTo(devices));
}
}
问题是,returns 是包含 3 个字段的响应。
我怎样才能 return 一个匹配接口的响应,所以 Observable<Array<Device>>
将只包含 2 个字段?
我想调用 getDevices()
方法并使用仅具有 id、名称字段的设备对象数组进行观察。
恐怕你必须手动操作。
getDevices(): Observable<Array<Device>> {
return timer(200).pipe(mapTo(devices),
map(arr=>arr.map(({name,id})=>({name,id})));
}