如何等待Angular 5 Observable?

时间:2018-01-25 16:41:42

标签: angular5

嗨)我正在使用Angular 5,我有配置服务。

...
@Injectable()
export class Configuration {
  public cultures = Array<Culture>();
  constructor(
    private cultureService: CultureService,
    private translate: TranslateService
  ) {
    this.cultureService.getAll().subscribe(
      data => {
        this.cultures = data.map(function(s) {
          return new Culture(s.id, s.code, s.name);
        });
        console.log(this.cultures);
      },
      error => console.log('& app.config ' + error + ' &'),
      () => {}
    );   
  }
}

我有DashboardComponent。在DashboardComponent中,从配置服务调用culture数组。但是当调用culture数组时,Configuration服务返回空文化数组。在Configuration service cultureService.getAll()的构造函数中,Observable方法正在运行,但它已经迟到了。问题:如何等待可观察的方法直到它完成?

...

@Component({
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
  langs = [];
  constructor(
    private translate: TranslateService,
    private configuration: Configuration
  ) {        
      console.log(configuration.cultures);
  }

  ngOnInit() {
  }

  changeLang(language: Culture): void {
    this.translate.use(language.code);
    localStorage.setItem('lang', language.code);
  }
}

2 个答案:

答案 0 :(得分:1)

这很奇怪。只有当有人对next()进行subscribe()时才会触发Observable。只有这样你才能从@Injectable() export class ConfigurationService { result: any; constructor(private $culture: CultureService) { this.$culture.getAll().subscribe(data => { this.result = data.map(x => { return new Culture(x); }); console.log(this.result); console.log(data); }); } 获得一些东西。 我复制了你的代码,它按预期工作。这是我对它的修改:

  getAll(): Observable<any> {
    return Observable.create(observer => {
      setTimeout(() => {
        observer.next([2, 3, 4]);
      }, 3000)
    });
  }

我的getAll()函数就是这个:

next()

如您所见,我模拟了Observable的延迟console.log()。正如预期的那样,next()只会在 $ cd [your working directory] $ docker run -it -v $(pwd):/usr/workspace joyzoursky/python-chromedriver:3.6-alpine3.7-selenium sh / # cd /usr/workspace 发生时发生

<强> Stackblitz demo here

如果这不能回答您的问题,请在那里复制您的问题,我会尽力帮助。

答案 1 :(得分:0)

        Try this 
        In Configuration service ----
        @Injectable()
        export class Configuration {
          public cultures = new BehaviorSubject(Array<Culture>());
          constructor(
            private cultureService: CultureService,
            private translate: TranslateService
          ) {
            this.cultureService.getAll().subscribe(
              data => {
                let res = data.map(function(s) {
                  return new Culture(s.id, s.code, s.name);
                });
                this.cultures.next(res);
              },
              error => console.log('& app.config ' + error + ' &'),
              () => {}
            );   
          }
        }

    In DashboardComponent -----
    @Component({
      templateUrl: './dashboard.component.html',
      styleUrls: ['./dashboard.component.scss']
    })
    export class DashboardComponent implements OnInit {
      langs = [];
      constructor(
        private translate: TranslateService,
        private configuration: Configuration
      ) {
          configuration.cultures.subscribe((value) => {
          console.log("Subscription got", value);
          });
      }

      ngOnInit() {
      }

      changeLang(language: Culture): void {
        this.translate.use(language.code);
        localStorage.setItem('lang', language.code);
      }
    }