【问题标题】:Firebase - Angularfire2 subscribe wait for response to return valueFirebase - Angularfire2订阅等待响应返回值
【发布时间】:2017-12-11 15:48:17
【问题描述】:

Angularfire2 的异步操作有问题。我想在我的 Firebase 数据库中创建一个新资源,但首先我想检查是否存在同名的资源并向前端返回一条消息。

问题是我无法将消息返回到subscribe 方法。 VS 抛出这个错误:

Severity    Code    Description Project File    Line    Suppression State
Error   TS2355  (TS) A function whose declared type is neither 'void' nor 'any' must return a value.

这是我的功能代码:

createInstance(instanceName: string): string {
      this.databaseService.getList('/Events/' + instanceName).subscribe(
          result => {
              var message;
              if (result.length === 0)
              {
                  this.databaseService.update('/Events/' + instanceName + '/Configuration', myObject);
                  message = "Instance created";
              }
              else
              {
                  message = "Instance already exists";
              }
              return message;
          });
  }

【问题讨论】:

    标签: firebase angularfire2 angular5


    【解决方案1】:

    您正在运行的函数是异步的,因此您可以subscribe 回复响应,以便在操作完成时得到通知。

    但是,您的函数是同步运行的,因此它会在数据库获取数据之前执行并返回,这会在稍后发生。

    所以你得到的错误是因为你的函数实际上没有返回任何东西,但它被声明为返回一个string,你只能在以后得到。

    一种解决方案是将您声明为Observable,就像您正在使用的数据库服务一样,并异步使用它。

    例如:

    // extra import you'll need
    import { Observable } from 'rxjs';
    
    createInstance(instanceName: string): Observable<string> {
        return Observable.create(observer => {
            this.databaseService.getList('/Events/' + instanceName).subscribe(result => {
                if (result.length === 0) {
                    this.databaseService.update('/Events/' + instanceName + '/Configuration', myObject);
                    observer.next('Instance created');
                } else {
                    observer.next('Instance already exists');
                }
                observer.complete();
            });
        });
    }
    

    然后你像这样消费它:

    createInstance('test').subscribe(message => {
        // here you go
    });
    

    【讨论】:

      猜你喜欢
      • 2018-04-27
      • 2023-02-06
      • 2019-08-01
      • 2021-07-16
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      相关资源
      最近更新 更多