javascript - 角度打字稿页面上的数组为空
问题描述
我正在用一个名为“getQuestionsWithInterviewId”的函数填充我的字符串“问题”,但是当我在 ngOnInit 和 ngAfterContentInit 方法中使用 console.log 调用它时,它看起来是空的。
import { Component, OnInit } from '@angular/core';
import { QuestionService } from '../_services/question.service';
import { Question } from '../_models/model';
@Component({
selector: 'app-interview',
templateUrl: './interview.component.html'
})
export class InterviewComponent implements OnInit {
questions: Question[]=[];
constructor(private questionService: QuestionService) {
}
ngOnInit(): void {
}
ngAfterContentInit() {
this.getQuestionsWithInterviewId(1);
console.log(this.questions);
$(".tab-wizard").steps({
headerTag: "h6",
bodyTag: "section",
transitionEffect: "fade",
titleTemplate: '<span class="step">#index#</span> #title#',
labels: {
finish: "end"
},
onFinished: function (event, currentIndex) {
alert("end");
}
});
}
getQuestionsWithInterviewId(interviewId: number) {
this.questionService.getQuestionsWithInterviewId(interviewId).subscribe(a => {
this.questions = a;
},
error => {
console.log(error);
});
}
}
但是当我在 component.html 页面上使用“问题”数组时,我可以看到结果。
如果我在“getQuestionsWithInterviewId”函数中执行 console.log 操作,我可以获得结果。
getQuestionsWithInterviewId(interviewId: number) {
this.questionService.getQuestionsWithInterviewId(interviewId).subscribe(a => {
this.questions = a;
console.log(this.questions);
},
error => {
console.log(error);
});
}
question.service.ts 页面;
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Question } from '../_models/model';
@Injectable({
providedIn: 'root'
})
export class QuestionService {
baseUrl: string = 'https://localhost:44388/api/questions/';
constructor(private http: HttpClient) {
}
getQuestionsWithInterviewId(interviewId: number): Observable<Question[]> {
return this.http.get<Question[]>(this.baseUrl +
"GetQuestionsWithInterviewId/" + interviewId);
}
}
解决方案
这是因为getQuestionsWithInterviewId
使用了 observable from questionService
。
questions
分配时填充this.questions = a
。当订阅被触发时会发生这种情况。仅在所有调用堆栈为空后才会触发订阅。所以这发生在ngAfterContentInit
完成执行之后。
要对来自订阅的数据执行操作,您必须在subscribe
回调中执行此操作。
更新
ngOnInit() {
this.questionService.getQuestionsWithInterviewId(1).subscribe(a => {
this.questions = a;
// this console log will do
console.log(this.questions);
// feel free to do your magic with questions here
},
}
推荐阅读
- python - 对模型和 CalibratedClassifierCV 使用相同的验证集
- javascript - HTML 按钮中的计时器(作为提交表单的重新发送按钮)
- reactjs - “无法读取未定义的属性‘切片’”在 onClick 处理程序中
- upload - 如何通过优酷授权我的应用程序将视频上传到最终用户的帐户?
- python - 如何解析在python中可能包含或不包含换行符的字符串?
- javascript - 在移动视图中将按钮更改为 dropdwon
- java - 制作内部列表的键与外部列表的值
- amazon-web-services - 创建服务目录我是 cloudformation 模板中的角色
- json - 如何从bash填充/更改格式良好的JSON文件的某些部分的特定未知字符串,保持格式不变?
- r - 我可以按数字类型对全球环境进行排序并将所有内容提取到一个 CSV 中吗?或者直接在 R 中从每列中的 500 多个值中创建一个数据表?