Angular 2 Typescript:是否可以将接口作为参数传递给函数?
发布时间:2020-12-17 17:27:22 所属栏目:安全 来源:网络整理
导读:我有以下问题:我从 JSON API中提取数据.我目前为每个数据模型(例如文章,用户等)提供服务,并为每个数据模型提供模型类.但这是疯狂的,不能真正维持.所以我想重构,以便为每个数据模型和一个统一的DataAPIService提供接口和模型类. 问题是,查询API的DataAPIServ
我有以下问题:我从
JSON API中提取数据.我目前为每个数据模型(例如文章,用户等)提供服务,并为每个数据模型提供模型类.但这是疯狂的,不能真正维持.所以我想重构,以便为每个数据模型和一个统一的DataAPIService提供接口和模型类.
问题是,查询API的DataAPIService中的函数不应返回JSON,而是返回已查询类型的对象或对象集合.所以我需要一种方法将接口或类型传递给服务的查询方法,然后初始化这种类型的新对象. 这可能吗?我有道理吗?这里有一些代码可以帮助理解我的意思并展示我目前的进展. import { Injectable } from '@angular/core'; import { AuthHttp } from 'angular2-jwt'; import 'rxjs/add/operator/map'; import { Config } from '../config/env.config'; @Injectable() export class DataAPIService { constructor( private authHttp: AuthHttp ) {} // This function will be called to retrieve data (for example from a Component). // I want to pass in the object type or interface so that I only have one // getIndex() function and not one for every data type. getIndex(page:number = 1,object_name:string,object_type) { return this.authHttp.get(Config.API_ENDPOINT + '/' + object_name + '?page=' + page) .map(res => res.json()) .map(res => { return this.fromJson(res.data,object_type); }); } // This function just checks which attributes are present in the object type // and fills a new object of this type with the values from JSON. // This is partly pseudo-code since I don't know how to solve this. fromJson(input_json: any,object_type) { // The next line is obviously not working. This is what I'm trying to figure out var object:object_type = new object_type(); var json_attributes = input_json.attributes; for (var key in json_attributes) { if (object.hasOwnProperty(key)) { object[key] = json_attributes[key]; } } object.id = input_json.id; return object; } } 解决方法
你可以做的是使用泛型(如果你不知道它们是什么,我建议使用谷歌搜索).
@Injectable() export class DataAPIService { constructor( private authHttp: AuthHttp ) {} // This function will be called to retrieve data (for example from a Component). // I want to pass in the object type or interface so that I only have one // getIndex() function and not one for every data type. getIndex<T>(page:number = 1,object_name:string): Observable<T> { return this.authHttp.get(Config.API_ENDPOINT + '/' + object_name + '?page=' + page) .map(res => res.json()); } 通过将T generic添加到您的方法中,您可以将返回类型定义为类型为T的值的Observable.res.json()将只创建一个对象,如果它返回给此方法的调用者,则我只是看到类型为T的值的可观察值.无需为接口编写这样的特定解析函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |