将数据从构造函数传递到同一组件

时间:2018-03-06 12:19:28

标签: angular angular5

我从assets文件夹中获取json文件。 我的文件名是testjson.json

我使用以下代码从文件夹中获取json文件。

  constructor(private router:Router,private http:Http) {
                this.http.get('http://localhost:4200/assets/testjson.json')
                 .subscribe(data => {
                          console.log(data);
                  });
  }

testjson.json 文件,

{
   "time": "03:53:25 AM",
   "milliseconds_since_epoch": 1362196405309,
   "date": "03-02-2013"
}

现在,我想将这个json数据用于组件类(Same component class),

export class DashboardComponent implements AfterViewInit {

  constructor(private router:Router,private http:Http) {
                this.http.get('http://localhost:4200/assets/testjson.json')
                 .subscribe(data => {
                          console.log(data);
                  });
  }

  // I want to use data here. 

 }

我在console.log(data);

中成功获得了testjson.json

2 个答案:

答案 0 :(得分:2)

你可以像创建一个额外的变量一样:

  export class DashboardComponent implements AfterViewInit {

  data: any;

  constructor(private router:Router,private http:Http) {
                this.http.get('http://localhost:4200/assets/testjson.json')
                 .subscribe(data => {
                          this.data = data;
                  });
  }

  //now you could use it where you want;

 }

答案 1 :(得分:1)

你不能按照你的期望去做。你有2个解决方案。

export class DashboardComponent implements AfterViewInit {

  constructor(private router:Router,private http:Http) {
                this.http.get('http://localhost:4200/assets/testjson.json')
                 .subscribe(data => {
                          console.log(data);
                          // you can do whatever you want here in this block
                  });
  }



 }

另一种加强回调函数的方法。

    export class DashboardComponent implements AfterViewInit {


      constructor(private router:Router,private http:Http) {
                    this.http.get('http://localhost:4200/assets/testjson.json')
                     .subscribe(data => {
                              console.log(data);
                              this.OnGetData(data);
                      });
      }



     }

public onGetData(data){// do your work in this method}