Angular2のコードと混同しています。 ts
私が持っているファイル:
import { Test } from "../../../../models/test";
import { TestService } from "../../../../services/test.service";
import { Job} from "../../../../models/job";
import { JobService } from "../../../../services/job.service";
export class TestTakeMcComponent implements OnInit {
company_name: string;
test: Test;
job: Job;
constructor(
private testService: TestService,
private jobService: JobService
) { }
ngOnInit() {
this.getTest();
this.getJob(this.test.id);
}
getTest(){
this.testService.getById(40).subscribe(
test => {
if(test.data.data.length != 0){
this.test = test.data.data[0];
}
}
);
}
getJob(id: number){
this.jobService.getJobByTestId(id).subscribe();
}
}
そして私のHTMLファイルには次のものがあります。
<h3 class="box-title">{{ test?.title }} </h3>
確かに、データバインディング {{ test?.title }}
動作しており、データを表示しています。しかし、別の関数の呼び出し中に getJob(this.test.id)
私の〜の上に ts
ファイル、それは未定義のパラメータを言います。 ビューに完全に表示されているときに、これがどのように未定義になったのですか?内部のデータを使いたかった this.test
他の関数への変数ですが、未定義なのでできません。 誰かが私と同じ問題を抱えていて、どのようにしてこの問題を修正したのですか?ありがとうございました。
回答:
回答№1は1これは、 console.log()
前に実行される this.test
割り当てられた値を取得します。実行は非同期です。つまり、同期コードの実行はすぐに続行されますが、後で実行するようにスケジュールされています。
{{ test?.title }}
は undefined
最初ですが後で更新されますが、変更は人間が認識するには速すぎます。
あなたが console.log()
値が表示されます
getTest(){
this.testService.getById(40).subscribe(
test => {
if(test.data.data.length != 0){
this.test = test.data.data[0];
console.log(this.test);
}
}
);
}
更新
export class TestTakeMcComponent implements OnInit {
company_name: string;
test: Test;
job: Job;
constructor(
private testService: TestService,
private jobService: JobService
) { }
ngOnInit() {
this.getTest().subscribe(val =>
this.getJob(this.test.id));
}
getTest(){
// add `return` and replace `subscribe` by `map`
return this.testService.getById(40).map(
test => {
if(test.data.data.length != 0){
this.test = test.data.data[0];
}
}
);
}
getJob(id: number){
this.jobService.getJobByTestId(id).subscribe();
}
}
回答№2の場合は1
コードを次のように置き換えます:
import { Test } from "../../../../models/test";
import { TestService } from "../../../../services/test.service";
export class TestTakeMcComponent implements OnInit {
company_name: string;
test: Test;
constructor(
private testService: TestService
) { }
ngOnInit() {
this.getTest();
// console.log(this.test);
}
getTest(){
this.testService.getById(40).subscribe(
test => {
if(test.data.data.length != 0){
this.test = test.data.data[0];
console.log(this.test);
this.getJob();
}
}
);
}
getJob(){
this.jobService.getJobByTestId(this.test.id).subscribe();
}
}
あなたはちょうど置いた console.log()
間違った場所で。
として this.testService.getById(40).subscribe
非同期部分なので、
ngOnInit() {
this.getTest();
// at this time we"ll not have this.test ;
// console.log(this.test);
}