2017-12-27 184 views
1

我试图做一个打字稿接口,为cryptocompare coinlist API创建界面(https://www.cryptocompare.com/api/data/coinlist/typescipt:为cryptocompare coinlist API

我已经尝试过目前这样的:

interface CoinListResponse { 
    Response: string, 
    Message: string, 
    BaseImageUrl: string, 
    BaseLinkUrl: string, 
    Type: number, 
    Data: Array<Coin> 
} 

现在,这部分作品但Data: Array<Coin>存在问题,因为Data不是数组而是对象。你可以在这里看到documenation:https://www.cryptocompare.com/api/#-api-data-coinlist-

这是我想解决什么: example code

这是硬币接口:

export interface Coin { 
    Id: number, 
    Url: string, 
    Name: string, 
    CoinName: string, 
    FullName: string, 
    Algorithm: string, 
    ProofType: string, 
    SortOrder: number 
} 

这可能吗?

非常感谢。

+0

但..数据是否有你正在返回'可观察'因为你是有原因的不处理数组? –

+0

@SurajRao我想用作数组 – DazDylz

回答

0

根据API JSON响应定义:

"Data": { 
     "LTC": { 
      "Id": "3808", 
      "Url": "/coins/ltc/overview", 
      "ImageUrl": "/media/19782/ltc.png", 
      "Name": "LTC", 
      "CoinName": "Litecoin", 
      "FullName": "Litecoin (LTC)", 
      "Algorithm": "Scrypt", 
      "ProofType": "PoW", 
      "SortOrder": "2" 
     } 
     ... 
    }, 

Data属性可以被建模为一个键 - 值对类型,其中关键是货币名称(string),值是​​类型的。

export interface CoinData { 
    [key: string]: Coin 
}; 

interface CoinListResponse { 
    Response: string, 
    Message: string, 
    BaseImageUrl: string, 
    BaseLinkUrl: string, 
    Type: number, 
    Data: CoinData 
} 
+0

嗯。这是更近一步,但现在我得到'[ts]运算符'<='不能应用于类型'硬币'和'数字'。' – DazDylz

+0

这是因为你必须通过名称访问特定的货币:'coin ['LTC' ] .SortOrder'。否则,你正在访问整个哈希集,其中包含多种货币及其数据。 –

+0

谢谢。我希望它是可迭代的。请参阅下面的我的回答。 – DazDylz

0

解决方案不必须中将sortOrder either.I认为这将是内部data.And另一个对象[ts] Operator '<=' cannot be applied to types 'Coin' and 'number'.

export function coins$(): Observable<any> { 
    const response = WebRequest.json<CoinListResponse>(`${API_BASE}/data/all/coinlist`); 
    return Observable.fromPromise(response) 
     .map(response => response.Data) 
     .map(coins => Object.values(coins).filter(coin => coin.SortOrder <= COIN_LIMIT)); 
};