我是Angular 2中的新手并试图完成超过5天
我试图在pageload之后使用服务中的数据,但数据总是未定义但在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 --!>
对不起如果我的问题让你感到困惑。
答案 0 :(得分:1)
您正在制作异步请求,因此您必须将代码放入其回调中 ,像这样
ngOnInit() {
this.Length();
}
Length(){
this._someservice .getLength()
.subscribe(
data => this.length = data,
error => {},
() => {
console.log("Length : "+this.length); // will not show undefined
this.UseLength();
}
);
}