首页 > 解决方案 > http.get() 传递 ID

问题描述

我正在尝试从通过打字稿中的 http.get() 调用的 URL 获取详细信息。我检索此详细信息的 URL 端点是一种localhost:8001\character\1234567890其中数字是字符 ID 的类型。

如果我在浏览器上测试,URL 会正确返回所有数据。

我的问题是关于打字稿函数调用。在 HTML 前面,我将函数调用为:

<a href="#{{character.id}}" (click)="characterDetail(character.id)">Read more</a>

然后,其余的功能是:

characterDetail(characterId: number) {
    this.asyncCharDetail = this.getCharacterDetail(characterId)
        .do(res => {
            console.log(res);
        })
        .map(res => res.results);
}



getCharacterDetail(characterId: number) {
    return this.http.get(this.characterDetailApiUrl + characterId,{})
        .map((res: Response) => res.json())
}

console.log(res)from first 函数不打印任何内容。characterId和 url 都是正确的,但不知道不检索字符详细信息的原因。

数据检索的第二部分显示在模式窗口上。

编辑:这里你有更多的代码:

private characterDetailApiUrl = 'http://localhost:8001/character/';
....
//To save the character details from Http get.
asyncCharDetail: Observable<string[]>;

characterDetail(characterId: number) {
    console.log('Character detail for ID ' + characterId);
    this.loading = true;
    this.asyncCharDetail = this.getCharacterDetail(characterId)
        .do(res => {
            console.log(res);
            this.loading = false;
        })
        .map(res => res.results);
    console.log(this.asyncCharDetail);
}

getCharacterDetail(characterId: number) {
    return this.http.get(this.characterDetailApiUrl + characterId )
        .map((res: Response) => res.json());
}

在 Html 前端文件上:

<a href="" (click)="characterDetail(character.id); $event.preventDefault()">Read more</a>

标签: angulartypescripthttp-get

解决方案


你必须订阅 Observable 才能让它做某事。

characterDetail(characterId: number) {
    this.getCharacterDetail(characterId)
        .do(res => {
            console.log(res);
        })
        .map(res => res.results)
        .subscribe(data => { 
           //...do something with data
        });

}

推荐阅读