Angular 2中带有Observable的http不能使用数据 [英] http with Observable in Angular 2 cant use data

查看:131
本文介绍了Angular 2中带有Observable的http不能使用数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是角度2和可观察对象的新手,但我想尝试一下.因此,我已经安装了angular-cli并进行了一个简单的测试项目.

i am new to angular 2 and to observables but i wanted to give it a shot. So i have installed the angular-cli and made a simple test project.

我要做的就是读取一个json文件并使用组件内部的数据(其初衷是提供服务,但我想从低端入手).

All i wanted it to do is read a json file and work with the data inside of a component (the first intention was to make a service but i wanted to start on a low basis).

所以我已经在assets/json文件夹(testjson.json)中创建了一个json文件:

So i have created a json file in the assets/json folder (testjson.json):

{
  "teststring": "test works"
}

然后我已经从我的content.component.ts文件中的angular和rxjs映射文件中导入了http:

then i have imported the http from angular and the rxjs map stuff inside of my content.component.ts file:

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {

  title: string = "Default";
  data;

  constructor(private http:Http) {
    http.get('assets/json/testjson.json').map(res => res.json()).subscribe(data => {this.data = data; this.title = data.teststring; console.log(this.data);});
  }

  ngOnInit() {

  }

}

到目前为止,该应用程序会打印出以下内容:

So far so good, the app prints out the following:

app works!

test works [object Object]

但是我想在整个组件中使用此数据,而不仅仅是在构造函数中使用.但是,如果我尝试在构造函数外部(在ngOnInit函数内部)console.log"this.data",它将在控制台中打印未定义的内容.

But i want to use this data in the whole component, not only in the constructor. but if i try to console.log "this.data" outside of the constructor (inside the ngOnInit function), it prints undefined in the console.

我知道,它必须与异步加载有关,但是不幸的是,我不知道如何告诉应用程序等待this.data填满.

I know, that it must have something to do with asynch loading but unfortunately i have no clue how to tell the app to wait until this.data is filled.

希望您能帮助我.当然,将来我需要一种执行这种工作的服务,并且不止一个组件应该从中获取数据.

I hope you can help me with that. Of course in the future i want a service which does that kind of stuff and more than one component should grab data from it.

提前谢谢!

推荐答案

  • 您应该将初始化代码移至初始化方法.
  • 回调完成后,您的数据将变为可用.在模板中,一旦有数据,就可以使用*ngIf在块内执行代码.只要*ngIf不等于true,内部代码就不会运行.
  • 运行console.log(data)的唯一方法是在回调内部或从回调调用,因为您必须等待数据加载完毕.
    • You should move the initialization code to the initialization method.
    • Your data becomes available once the callback completes. In your template you can use *ngIf to execute code inside a block once there is data. As long as the *ngIf does not eval to true the inner code will not run.
    • The only way you can run console.log(data) is from inside the callback or called from the callback because you have to wait until the data is loaded.
    • content.component.html

      <div *ngIf="data">
        <span>{{data.teststring}}</span>
      </div>
      

      content.component.ts

      export class ContentComponent implements OnInit {
      
        title: string = "Default";
        data: any = null;
      
        constructor(private http:Http) {
        }
      
        ngOnInit() {
          this.http.get('assets/json/testjson.json')
            .map(res => res.json())
            .subscribe(data => {
              this.data = data;
              this.title = data.teststring;
              console.log(this.data);
            });
        }
      }
      


      编辑

      对于下面的评论:如果您抽象出对服务的http调用,则可以看到完全相同的逻辑仍然适用.您仍在使用数据承诺的概念,一旦完成,您就可以订阅该承诺.唯一的区别是http调用被抽象到另一个类.


      Edit

      In response to the comment below If you abstract out the http call to a service you can see the exact same logic still applies. You are still using the concept of a promise of data and that you can subscribe to that promise once it has completed. The only difference here is the http call is abstracted to a different class.

      content.component.ts

      export class ContentComponent implements OnInit {
      
        title: string = "Default";
        data: any = null;
      
        // inject service
        constructor(private contentService:ContentService) {
        }
      
        ngOnInit() {
          this.contentService.getData()
            .subscribe(data => {
              this.data = data;
              this.title = data.teststring;
              console.log(this.data);
            });
        }
      

      服务

      export class ContentService {
      
        constructor(private http:Http) {
        }
      
        getData(): IObservable<{teststring:string}> { // where string can be some defined type
          return http.get('assets/json/testjson.json')
            .map(res => res.json() as {teststring:string});
        }
      

      这篇关于Angular 2中带有Observable的http不能使用数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆