【问题标题】:Subscribing to service returns `undefined` values订阅服务返回“未定义”值
【发布时间】:2018-08-26 20:31:10
【问题描述】:

我正在尝试订阅一个尝试使用以下对象访问 REST 后端的服务。

export class Country {

    iso: String;
    iso3: String;
    name: String;
    niceName: String;
    numCode: number;
    phoneCode: number;

    constructor(values: Country = {}) {
        Object.assign(this, values);
    }
}

这是从API中获取数据的服务方法,数据被成功获取到map()函数中。

public getCountries(): Observable<Country[]> {
    return this.http.get(COUNTRY_URL).pipe(
            map(response => {
                const countries = response.json()._embedded.countries;
                return countries.map((country) => { new Country(country) });
            }),
            catchError(this.handleError)
        );
}

这是订阅服务的消费者。

countries: Country[] = [];

constructor(private countryService: CountryService) {
    countryService.getCountries()
        .subscribe(countries => { 
            this.countries = countries;
    });
}

country 变量最终成为 undefined 对象的数组。

其他信息

我正在使用 Angular 6RXJS6 并遵循迁移 指导 here

这是一个示例 API 响应。

{
    "_embedded" : {
        "countries" : [ ... ]
    },
    "_links" : {
        "first" : {
            "href" : "http://localhost:8080/api/countries?page=0&size=20"
        },
        "self" : {
            "href" : "http://localhost:8080/api/countries{?page,size,sort}",
            "templated" : true
        },
        "next" : {
            "href" : "http://localhost:8080/api/countries?page=1&size=20"
        },
        "last" : {
            "href" : "http://localhost:8080/api/countries?page=11&size=20"
        },
        "profile" : {
            "href" : "http://localhost:8080/api/profile/countries"
        },
        "search" : {
            "href" : "http://localhost:8080/api/countries/search"
        }
    },
    "page" : {
        "size" : 20,
        "totalElements" : 239,
        "totalPages" : 12,
        "number" : 0
    }
}

任何人都可以看到我的代码有任何问题吗?任何帮助将不胜感激。

【问题讨论】:

  • 如果你使用 Angular6 那么你不应该做response.json()这样的事情
  • 有什么解决方法吗?
  • 看看response是什么
  • 不应该反过来吗? Object.assign(this, values);
  • 结果相同。事实上,从values 分配单个字段会产生相同的结果。这可能与RXJS6.0 中的订阅更改有关,但我不确定出了什么问题。

标签: angular typescript rxjs6


【解决方案1】:

看起来您在new Country(country) 之前缺少return(或者,删除周围的花括号)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-03
    • 2021-04-27
    • 2018-10-19
    • 2020-08-12
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多