Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使订阅在Angular 4中等待主题_Angular_Rxjs_Observable_Angular2 Observables_Subject Observer - Fatal编程技术网

使订阅在Angular 4中等待主题

使订阅在Angular 4中等待主题,angular,rxjs,observable,angular2-observables,subject-observer,Angular,Rxjs,Observable,Angular2 Observables,Subject Observer,我的HTML中有一个文本字段,它根据输入的文本实时调用后端服务。如果用户输入类似“abc”的内容,我的服务将返回一个具有此“abc”名称的对象数组 我使用Observable和Subject进行此操作,并在我的组件中返回已处理的服务。请看代码 HTML代码 import { Subject } from 'rxjs/Subject'; searchString$ = new Subject<string>(); constructor() { this.searchSt

我的HTML中有一个文本字段,它根据输入的文本实时调用后端服务。如果用户输入类似“abc”的内容,我的服务将返回一个具有此“abc”名称的对象数组

我使用Observable和Subject进行此操作,并在我的组件中返回已处理的服务。请看代码

HTML代码

import { Subject } from 'rxjs/Subject';

searchString$ = new Subject<string>();

constructor() {

    this.searchString$.debounceTime(500)
    .distinctUntilChanged()
      .map(searchText => {
        return this.backEndService.fetchSearchStringData(searchText);
      })
      .subscribe(result => {
        console.log('result');
        console.log(JSON.stringify(result));

      });
}

部件代码

import { Subject } from 'rxjs/Subject';

searchString$ = new Subject<string>();

constructor() {

    this.searchString$.debounceTime(500)
    .distinctUntilChanged()
      .map(searchText => {
        return this.backEndService.fetchSearchStringData(searchText);
      })
      .subscribe(result => {
        console.log('result');
        console.log(JSON.stringify(result));

      });
}
从'rxjs/Subject'导入{Subject};
searchString$=新主题();
构造函数(){
此.searchString$.debounceTime(500)
.distinctUntilChanged()
.map(searchText=>{
返回此.backEndService.fetchSearchStringData(searchText);
})
.订阅(结果=>{
console.log('result');
log(JSON.stringify(result));
});
}
当我键入“abc”时,它调用这个fetchSearchStringData方法。服务调用只是简单的restService.post调用,然后设置对象是可观察的。使用该数据过滤某些内容并返回最终确定的数组

但是我的组件。订阅我们第一次并且只有一次被调用,它显示了未定义的值。(在这里我得到安慰。记录“结果”)

我如何确保在订阅组件时,一旦数据从服务中返回,我就可以获得数据


提前感谢。

除非您发布代码说明如何拨打
fetchSearchStringData
电话,否则我无法确定。但在内心深处,你需要回报一个承诺或一个可观察到的东西。看起来您没有返回任何内容,因此
consolte.log
打印
undefined

然后可以使用
switchMap
将结果展开到流中

this.searchString$.debounceTime(500)
  .distinctUntilChanged()
  .switchMap(searchText => {
    return this.backEndService.fetchSearchStringData(searchText);
  })
  .subscribe(result => {
    console.log('result');
    console.log(JSON.stringify(result));
  });

在尝试此swithcMap()之后,流将提供服务,但现在它不会出现在subscribe中。这意味着它不是在这里打印console.log(结果)。我认为在使用SwitchMap之后,它不知何故被困在了服务中。
fetchSearchStringData
功能可能有问题。使用SwitchMap有效。是的,我没有返回。将服务的响应映射到此组件,并且它工作顺利。