如何在组件中使用来自服务的数据?

How to use data from service in component?

我是 Angular 2 的新人,我尝试用 5 天多的时间完成这个

我试图在页面加载后使用来自服务的数据,但数据始终未定义,但它显示在 html 页面中。长度值来自服务器端。 (当我尝试从服务中获取 json 和 console.log 时也会发生这种情况)

service.ts

import {Injectable} from "angular2/core"
import {Http, Response} from 'angular2/http';
import 'rxjs/Rx'

@Injectable()
export class Someservice {

   getLength(){
     this.getLength = "url" 
     return this.http.get(this.getLength).map(res => res.text()); // data should be "1" or "2" or other text
   }
}

component.ts

import {Component, OnInit} from 'angular2/core';
import {Someservice} from '../services/service';

@Component({
selector: 'showcomponent',
templateUrl: '/components/somecomponent.html',
providers: [Someservice]
})

export class SomeComponent implements OnInit {

   length:number;

   constructor(private _someservice: Someservice){
      this._someservice = _someservice;
   }

   ngOnInit() {
      this.Length();
      this.UseLength();
   }

   Length(){
      this._someservice .getLength()
        .subscribe(
        data => this.length = data
        );

        console.log("Length : "+this.length); //show undefined
   }

   // I want to use length in this
   UseLength(){
       console.log("Length : "+this.length); // still undefined

       for(var i =0; i< this.length< i++){
          console.log("i: "+ i) // nothing run in here because it's undefined
       }

       console.log("Done");
   }
}

View.html

<input type = "text" [ngModel]="length" /> <!-- show length text --!>

抱歉,如果我的问题让您感到困惑。

您正在发出异步请求,因此您必须将代码放入它的回调中 , 像这样

ngOnInit() {
  this.Length();
}

Length(){
      this._someservice .getLength()
        .subscribe(
        data => this.length = data,
        error => {},
        () => {
                  console.log("Length : "+this.length); // will not show undefined
                  this.UseLength();
              }
        );
   }