简体   繁体   English

使用 map 转换值时,Observable 始终未定义

[英]Observable is always undefined when transform the value using map

I'm trying to understand why when I transform the observable it comes up undefined in the console log even though I know it has values assigned to it.我试图理解为什么当我转换 observable 时它在控制台日志中出现未定义,即使我知道它有分配给它的值。

Http Request Http 请求

getLibraryCardPeople(bookName: String): Observable<people[]> {
return this.http.get<LibraryCard>(url).pipe(map(results => results.people));
}

JSON response JSON 回复

book : "LOTR"
people : [
    {"name" : "joe", "age" : 20 , "Location": [...]},
    {"name" : "sarah", "age" : 16 , "Location": [...]}
]

When I execute the function and try and observe the people array is always undefined in the console log.当我执行 function 并尝试观察 people 数组在控制台日志中始终未定义。 However, If I don't map, I can see the entire JSON Response is defined.但是,如果我没有 map,我可以看到整个 JSON 响应已定义。

You need to subscribe to the httpClient.您需要subscribe httpClient。 First subscribe will activate the http call so to say.第一次subscribe将激活 http 电话。

getLibraryCardPeople(bookName: String): Observable<people[]> {
  return this.http.get<LibraryCard>(url);
}

Then in your component:然后在你的组件中:

this.myService.getLibraryCardPeople.subscribe(data => {
  data.pipe(map(results => results.people));
})

This is the normal way to use HttpClient .这是使用HttpClient的正常方式。 What you can do, too, is to use toPromise from RxJS .您也可以使用toPromise中的RxJS Read all abouthere . 在这里阅读所有内容。 A example:一个例子:

this.http.get<LibraryCard>(url).toPromise()
        .then(res => console.log(res))
        .catch(err => { console.log ('error');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM