Angular 2字符串在第一次迭代时仍未定义

时间:2016-05-25 08:44:30

标签: asp.net-mvc typescript angular

我正在尝试通过http.get从服务器获取一个对象并且它可以工作,但是在第一次迭代时字符串仍未定义。 The full object

整数没问题,问题只出在字符串上。

        this.http.get("/Home/getRoom", { headers: headers }).map(res => res.json()).subscribe(q => {
    this.timecount = q.timeperquestion; this.player1id = JSON.stringify(q.player1id); this.player2id = q.player2id; }, err => console.error(err),
        () => console.log('Complete'));

在函数的第一次迭代之后显示字符串。

编辑:

这是班级:

class AppComponent implements AfterViewInit {
public answered = false;
public title = "loading question...";
public options = [];
public correctAnswer = false;
public working = false;
public timecount=15;
public timer;
public roomID;
public player1id;
public player2id;

constructor( @Inject(Http) private http: Http, private Ref: changeDetectorRef) {


}


nextQuestion() {

    this.working = true;
    this.answered = false;
    this.title = "loading question...";
    this.options = [];
    var headers = new Headers();
    headers.append('If-Modified-Since', 'Mon, 27 Mar 1972 00:00:00 GMT');
    this.http.get("/Home/getRoom", { headers: headers }).map(res => res.json()).subscribe(q => {
    this.timecount = q.timeperquestion;
    this.player1id = JSON.stringify(q.player1id);
    this.Ref.detectChanges();
    },
        err => console.error(err),
        () => console.log('Complete'));

编辑2: 好吧看起来字符串一切正常,当我尝试用{{player1id}}显示它时,它甚至在第一次迭代时显示正确的值。 “问题”仅限于我用来检查字符串的console.log(player1id),它只在一次迭代后才起作用。 感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您可以强制使用ChangeDetectorRef类运行更改检测。注入它并调用其detectChanges方法:

constructor(private changeDetectorRef:changeDetectorRef) {
}

someMethod() {
  this.http.get("/Home/getRoom", { headers: headers }).map(res => res.json()).subscribe(q => {
    this.timecount = q.timeperquestion;
    this.player1id = JSON.stringify(q.player1id);
    this.player2id = q.player2id;
    this.changeDetectorRef.detectChanges();
  },
  err => console.error(err),
  () => console.log('Complete'));
}

答案 1 :(得分:0)

属性为undefined的原因是由于它们实际上定义。只需将它们设置为空字符串= ""或将其声明为: string,如下所示:

class AppComponent implements AfterViewInit {
   public player1id: string;
   public player2id = ""; // I usually prefer this as it is assigned a value
   // Omitted for brevity...
}

TypeScript 中,您应该声明您打算使用的类型,或者指定它以便推断它。否则你会错过 TypeScript 的所有荣耀。