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のすべての素晴らしさを少し逃してしまうことになります。
