简体   繁体   English

使订阅在 Angular 4 中等待主题

[英]Making Subscribe to wait in Angular 4 for Subject

I have a text field in my HTML which calls back-end service in real time based on text entered.我的 HTML 中有一个文本字段,它根据输入的文本实时调用后端服务。 If a user enters something like 'abc', my service returns an object array which has this 'abc' name.如果用户输入诸如“abc”之类的内容,我的服务将返回一个具有此“abc”名称的对象数组。

I am using Observable and Subject for this and I am returning processed service in my component.我为此使用了 Observable 和 Subject,并且我正在我的组件中返回已处理的服务。 Please see the code.请看代码。

HTML Code HTML代码

<input size="30" type="text" (keyup)="searchTerm$.next($event.target.value)">

Component Code组件代码

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));

      });
}

When II type 'abc' then it calls this fetchSearchStringData method.当 II 输入 'abc' 时,它会调用这个fetchSearchStringData方法。 The service call is nothing but simple restService.post call and then setting the object is observable.服务调用只不过是简单的 restService.post 调用,然后设置对象是可观察的。 Using that data to filter something and returning the finalized array.使用该数据过滤某些内容并返回最终的数组。

But my component .subscribe us getting called first and only one time and it shows undefined value.但是我的组件 .subscribe 我们第一次并且只有一次被调用,它显示未定义的值。 (Where I am consoled.logging 'result'). (我被安慰的地方。记录'结果')。

How do I make sure I get the data once it gets a return from service in my subscribe of the component?一旦数据从我订阅的组件中获得服务返回,我如何确保获得数据?

Thanks in advance.提前致谢。

I cannot be sure unless you post code on how you make the fetchSearchStringData call.除非您发布有关如何进行fetchSearchStringData调用的代码,否则我无法确定。 But inside you need to return a Promise or Observable.但是在内部你需要返回一个 Promise 或 Observable。 It looks like you're not returning anything, thus consolte.log prints undefined .看起来您没有返回任何内容,因此consolte.log打印undefined

Then you can use switchMap to unwrap the result into the stream.然后您可以使用switchMap将结果解包到流中。

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

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

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