網站搜尋

asp.net mvc - Angular 2 字串在第一次迭代時仍為未定義


我正試圖通過 http.get 從伺服器獲取一個對象,它可以運作,但在第一次迭代時字串仍然是未定義的。完整對象

整數沒問題,問題只出在字串上。

        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),它只有在一次迭代後才會生效。感謝你嘗試幫助!

答案#1

你可以使用 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'));
}

答案#2

這些屬性是 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 的所有優點。