【问题标题】:http.get() passing IDhttp.get() 传递 ID
【发布时间】:2018-10-13 17:31:54
【问题描述】:

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

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

我的问题在于 typescript 函数调用。在 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) 不打印任何内容。 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>

【问题讨论】:

    标签: angular typescript http-get


    【解决方案1】:

    我已经从 2 个函数更改为 1 个函数,现在我从角色中获得了一些数据。现在作为@CornelC 的建议工作

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

    现在我正在从前端调用该函数,但需要显示一个带有检索数据的模式窗口

    【讨论】:

    • 您获得数据是因为您订阅了(正如我建议的那样),而不是因为您从 2 种方法更改为 1 种方法
    【解决方案2】:

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

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

    【讨论】:

    • 嗯,我已经定义了asyncCharDetail: Observable&lt;string[]&gt;;
    【解决方案3】:

    return this.http.get(this.characterDetailApiUrl + characterId,{})

    只是 URL 应该没问题。你能检查一下你删除,{}后得到了什么吗?所以return this.http.get(this.characterDetailApiUrl + characterId)

    如果您需要完整回复,请尝试将 {} 替换为 { observe: 'response' }

    【讨论】:

    • 如果删除 {} 相同的结果...将编辑代码以提供有关该问题的更多信息
    猜你喜欢
    • 1970-01-01
    • 2016-03-08
    • 2020-02-14
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多