Arrays 使用角度传感器从服务中提取数据

Arrays 使用角度传感器从服务中提取数据,arrays,json,angular,extract,subscribe,Arrays,Json,Angular,Extract,Subscribe,我试图用angular从json响应服务中提取firstname字段,并返回一个充满firstname的数组 这是json对象: { "hits": { "hits": [ { "_id": "BKZujHgB0urOc7uDCrf5", "_index": "names&qu

我试图用angular从json响应服务中提取firstname字段,并返回一个充满firstname的数组

这是json对象:

{
    "hits": {
        "hits": [
            {
                "_id": "BKZujHgB0urOc7uDCrf5",
                "_index": "names",
                "_score": 1.0,
                "_source": {
                    "firstname": "Alicia"
                },
                "_type": "_doc"
            },
            {
                "_id": "BaZujHgB0urOc7uDL7e2",
                "_index": "names",
                "_score": 1.0,
                "_source": {
                    "firstname": "Alice"
                },
                "_type": "_doc"
            }
        ]
        
}

我创建了一个服务来使用返回json对象的webservice,而不使用可观察对象。appService.ts

public autoComplete(name: string) {

    const params = new HttpParams()
        .set('name', name);
    return this.httpClient.get(this.host, { params});
  
在app.component.ts中,我创建了一个调用服务的函数,并在ngOnInit()中实现了它,我对自动完成的角度材质进行了一些修改。但我总是会出现错误,无法读取未定义的属性“hits”

ngOnInit() {
   this.seachText.valueChanges.pipe(
      startWith(''),
      // delay emits
      debounceTime(300),
      // use switch map so as to cancel previous subscribed events, before creating new once
      map(value => this.lookup(value))
      ).subscribe(value => this.results$ = value);
   this.names = this.results$.hits.hits.map(h => h._source.firstname);

   console.log('resultat :', this.names);

  } 

我不知道如何更正错误,但我想我使用的从服务提交的json对象提取数据的方法是错误的。问题是,您的流是非同步的,因此在分配名称时,肯定从未发出

要解决此问题,可以使用第二个贴图操作符,例如。 通过这种方式,您可以根据自己的喜好更改输出,最终值就是您所期望的

this.searchText.valueChanges
.烟斗(
startWith(“”),
去BounceTime(300),
映射(值=>this.appService.autoComplete(值)),
map(results=>results.hits.hits.map(hit=>hit.\u source.firstname))
)
.subscribe(value=>(this.results=value));
查看StackOverflow上的此恢复:


如果您希望自动完成方法返回一个可观察的值,那么在使用它时,只需将map替换为switchMap

首先,让我使用一个代码片段来简化错误

let a;

of(2).subscribe((res) => {
   a = res;
   console.log("res");  // Async code, executed after sync code
})

console.log(a); // syn code. This log is excuted first
输出将是

// undefiend 
// 2;
在您的例子中,您使用
results.hits
,然后它才会收到值。它实际上做的是读取未定义的命中数。这就是错误发生的地方


修复错误时,需要考虑<强>移动<强> >代码> .NAMEST=此。结果$.HIST.HIST.MAP(H= > H.So.Field.FrestNeNT);<将>编码到obverable订阅的内部,或使用obersable操作符异步设置值。

您需要在回调内部执行此操作。阅读规范感谢您的响应,但仍然存在同样的问题,无法读取未定义此自动完成方法的属性“hits”
public autocomplete(name:string){const params=new HttpParams().set('name',name);返回this.httpClient.get(this.host,{params});}
我不知道问题出在哪里我担心如果不提供更多的上下文,我们将无法在这方面提供更多帮助。ok@Simon,这是我的app.component.html`{{option}}`tslint在hits下面画一条下划线,告诉我“属性'hits'不存在于'Observable'类型上”。对于lint,您应该强类型地键入对象或使用任何属性。至于运行时错误,首先应该删除异步管道,因为结果是不可观察的到我的订阅内部,但仍然有相同的错误无法读取未定义的属性“hits”。这是我的完整ngOnInit()
ngOnInit(){this.searchText.valueChanges.pipe(startWith(“”)、debounceTime(300)、map(value=>this.appService.autoComplete(value))。订阅((value)=>{this.results=value;this.names=this.results.hits.hits.map(h=>h.(u source.firstname);}}