为什么 subscribe 方法返回 Subscriber 而不是响应值 下一期:来自后端的undefined

问题描述

在我的应用程序中,根据节点服务器中可用的配置 ID 检索用户配置。

  exports.getConfig() =(req,res) => {
 return res.status(200).send(id) -> where id is been read from configuration file 
}

在服务中,我收到了读取配置文件中的属性调用

      getUserConfig():any {
        this.http.get('/config/user',{responseType:'text'}).subscribe(data => {
       //console.log(data) ----- prints undefined 
        data
        )
        }

在 ts 中,我将用户配置存储在一个变量中,如下所示

let userConfigValue = this.configService.getUserConfig();
//console.log(userConfigValue) --- prints subscriber object

我希望 userConfigValue 为“1200”,即来自 file 的值。我在这里做错了什么。如何在我的角度组件中获取值。

解决方法

这不是 RxJS Observable 模式的工作方式。任何直接依赖于 observable 发出的异步数据的语句(例如您对 userConfigValue 的赋值)都必须在订阅内。

在您的情况下,您需要从调用中返回 observable 并在需要响应的地方订阅。

import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

getUserConfig(): Observable<any> {    // <-- return `Observable`
  this.http.get('/config/user',{ responseType:'text' }).pipe(
    tap((value: any) => console.log(value))   // <-- use `tap` for side effects (like logging)
  );
}
userConfigValue: any;

this.configService.getUserConfig().subscribe({
  next: (value: any) => {
    this.userConfigValue = value;
    // other statements that depend on `this.userConfigValue`
  },error: (error: any) => {
    // error handling
  }
});

下一期:来自后端的undefined

这可能与前端无关。确保在从服务器返回之前定义了 id 变量

exports.getConfig = (req,res) => {  // <-- parenthesis to `getConfig` isn't required
  console.log(id);  // <-- make sure here it isn't `undefined`
  return res.status(200).send(id);
}