【问题标题】:Getting [Object Object] in angular2 application在angular2应用程序中获取[Object Object]
【发布时间】:2018-04-19 13:48:27
【问题描述】:

我已经使用ngrx/effects 开发了angular2 应用程序来进行http 调用。我使用GIT 作为参考应用程序。一旦响应来自 http,我就无法在屏幕上显示它。它显示[object Object]。这是我的代码。

链接到component.html的HTML页面

<div class="container">
<div class="left-container cf">
<mat-tab-group>
    <mat-tab label="Configuration">{{jsons}}</mat-tab>
    <mat-tab label="Captured Output">
    </mat-tab>
</mat-tab-group>
</div>
</div>

组件.ts

        export class ExperimentDetailsComponent implements OnInit {

      jsons: Observable<any>;
      isLoading: Observable<any>;

      constructor(
        private store: Store<fromStore.State>
      ) {
        this.isLoading = store.select(fromStore.getIsLoading);
        this.jsons = store.select(fromStore.getJson);
        console.log(this.jsons)
      }

      ngOnInit() {
        this.store.dispatch(new jsonAction.GetJson());
        // this.jsons = this.store.select(fromStore.getJson);
      }
    }

Effects.ts

        export class GetJsonEffects {

      @Effect() json$ = this.actions$.ofType(Act.GET_JSON)
        .map(toPayload)
        .withLatestFrom(this.store$)
        .mergeMap(([ payload, store ]) => {

          return this.http$
            .get(`http://localhost:4000/data/`)
            .map(data => {
              return new Act.GetJsonSuccess({ data: data })
            })
            .catch((error) => {
              return Observable.of(
                new Act.GetJsonFailed({ error: error })
              );
            })
        });


      constructor(
        private actions$: Actions,
        private http$: HttpClient,
        private store$: Store<fromStore.State>
      ) {}
    }

【问题讨论】:

  • 你的代码中哪一部分与[Object Object]相关。它在哪里显示?预期的行为是什么?
  • 如果要显示json对象可以使用json管道:{{jsons|json}}
  • 感谢您的回复。如果我使用 {{jsons | json}} 我收到错误 - 错误类型错误:将循环结构转换为 JSON

标签: html angular rest ngrx-effects


【解决方案1】:

如您所见,store.select() 的结果是一个 observable。您不能直接将数据绑定到它。

您可以:

使用 async 管道让 UI 为您订阅 observable 并提取数据,例如:

<mat-tab label="Configuration">{{jsons | async}}</mat-tab>

或者自己订阅 observable。

export class ExperimentDetailsComponent implements OnInit {

     jsonSubscription = store.select(fromStore.getJson)
          .subscribe(jsons => this.jsons = jsons);

    ngOnDestroy() {
      this.jsonSubscription.unsubscribe();
    }
      jsons: any;

     // ...
}

这是一回事:

如果您使用Http 服务(来自@angular/http 模块):

另一件事是您返回的是 Response 对象,而不是从中提取的 JSON。您效果中的map() 需要调用data.json()。喜欢:

      return this.http$
        .get(`http://localhost:4000/data/`)
        .map(data => {
          return new Act.GetJsonSuccess({ data: data.json() })
        })

或者,根据我的喜好,添加另一个 map() 以使事情清楚:

      return this.http$
        .get(`http://localhost:4000/data/`)
        // You could also create an interface and do:
        //   `response.json() as MyInterfaceName` 
        //   to get intellisense, error checking, etc
        .map(response => response.json())
        .map(data => {
          return new Act.GetJsonSuccess({ data: data })
        })

如果您使用HttpClient 服务(来自@angular/common/http 模块):
(在 Angular v4.3+ 中可用)

在这种情况下,您不需要自己致电 .json(),它会为您完成,所以您不需要先拨打 .map() 我建议。

您还可以通过调用get() 来告诉 TypeScript 您希望 JSON 匹配的类型,如下所示:

      return this.http$
        .get<MyInterfaceName>(`http://localhost:4000/data/`)
        .map(data => {
          return new Act.GetJsonSuccess({ data: data.json() })
        })

get&lt;MyInterfaceName&gt;() 位将使 Angular 告诉 TypeScript JSON 对象与 MyInterfaceName 匹配,因此您将获得基于此的智能感知和错误检查(仅在编译时,无论如何这些都不会影响运行时)。

HttpClient Documentation

【讨论】:

  • 嗨,Meligy,感谢您的回复。我尝试了您提到的更改。我在 Effects.ts 中遇到了一些错误 属性 'json' 在类型 'Object' 上不存在。
  • this.http$.get(localhost:4000/data) 应该返回Observable&lt;Response&gt;,所以.map(response =&gt; ...) 应该有response 作为Response 而不是Object。当您将鼠标悬停在它上面时,您看到的是这样的吗?您的真实代码与此处发布的代码不同吗?
  • 另外,也许你有太多的括号或者你的 mergeMap() 应该包含所有这些代码的东西被关闭了,map() 在那之后运行。确保在.get(localhost:4000/data) 之后直接调用它,并且get() 调用只有一个右括号
  • 嗨,Meligy,发布的代码和我使用的代码是相同的。是的,http.get() 返回一个对象。在那个对象中 .json() 方法不存在。并且使用 Redux Devtool 我检查了状态Json Success,我能够看到 json 数据。我也检查了括号。我在显示来自商店的数据时遇到问题。
  • 看来您使用的是HttpClient 而不是Http(在Angular 4.3+ 中,从@angular/common/http 导入),它为您执行.json()。在这种情况下,您不需要它。并且只需要async 管道。顺便说一句,在HttpClient 中,您可以像这样调用get() .get&lt;MyInterfaceName&gt;(localhost:4000/data) 所以TypeScript 使用这种类型而不是对象。这在运行时没有任何作用,只是告诉 TypeScript 使用 MyInterfaceName 进行智能感知/错误检查等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 2020-06-17
  • 2020-11-17
  • 1970-01-01
  • 2014-09-13
  • 1970-01-01
相关资源
最近更新 更多