为什么请求返回的数据比插入的接口多?



我正在请求一个包含多个值的 API,但我不需要它们。

为此,我创建了接口,以便能够键入和使用正确的对象。

但是,我的对象变得"脏",因为除了接口值之外,它还会转到我不想从 API 中获得的其他值。

怎么办?

例:

IApiData {
example 1: {
hello: string;
}
example 2: [{ hello2: string; }]
}

然后在请求的结果中,我得到这个:

IApiData {
example 1: {
hello: '1',
hello2: '2'
}
example 2: [{
hello2: '2',
hello3: '3'
}]
}

总之,我所做的是这样的:

服务要求:

getLastFiveDays(cityLat: number, cityLng: number): Observable<IWeatherLastFiveDays> {
return this.http.get<IWeatherLastFiveDays>(`${this.endpoint}/onecall/timemachine`, {
headers: this.headers,
params: {
dt: this.dateUtils.getLastFiveDaysInSeconds().toString(),
lat: cityLat.toString(),
lon: cityLng.toString(),
},
});
}

店铺效果:

getAllConditions$ = createEffect(() =>
this.action$.pipe(
ofType(action.GET),
switchMap(({ cityName, countryIsoCode, cityLat, cityLng }) =>
forkJoin([this.backendService.getLastFiveDays(cityLat, cityLng), this.backendService.getNextFiveDays(cityName, countryIsoCode, cityLat, cityLng)]).pipe(
map(results => {
const lastFiveDaysResult = results[0];
const nextFiveDaysResult = results[1];
return action.GET_SUCCESS({
weather: {
id: cityName,
nextFiveDays: nextFiveDaysResult,
currentDay: lastFiveDaysResult.current,
lastFiveDays: lastFiveDaysResult.hourly,
},
});
}),
catchError(error =>
of(
action.GET_FAIL({
error: {
status: error.cod,
message: error.message,
},
})
)
)
)
)
)
);

我认为在你的问题中有两个要点要提。

首先,接口是一个合约,你应该以这种方式使用。换句话说,"脏"的东西应该无关紧要,重要的是对象履行了合同。

第二,引用网络,

TypeScript 是 JavaScript 的类型化超集,可编译为纯 JavaScript。

我想说的是,你应该把TypeScript看作是一个非常好的软件构建工具,TypeScript一直存在到它编译。换句话说,在运行时没有类型检查,如果不匹配,则在绑定访问不存在或不符合预期的内容时将出现错误。

保持最小对象以履行接口协定的简单方法,

interface ApiData {
example1: {
hello: string;
}
example2: [
{
hello2: string;
}
]
}
function minObjForApiData (obj) {
const example1 = { hello: obj.example1.hello };
const example2 = obj.example2.map(v => { hello2: v.hello2});
return {
example1,
example2
};
}

最新更新