简体   繁体   English

Angular 11:模板未在 http 请求订阅上更新,即使使用 changedetector()

[英]Angular 11 : Template not updating on http request subscription even with changedetector()

I'm stuck into this problem my template is not beeing updated with the new values from the subscription even it's updated when I console Log it我陷入了这个问题我的模板没有使用订阅中的新值进行更新,即使它在我控制台时更新了记录它

In service:在役:

getExam(teacherUsername:string,courseCode:string,examID:number){
    return this.http.post<{error:boolean,message:string,exam?:Quiz}>('https://the url goes here',
    {
      teacherUsername:teacherUsername,
      courseCode:courseCode,
      examID:examID
    })}

in the component:在组件中:

    quiz!:Quiz;
    loadQuiz(){
    this.courseService.getExam("getTeachernameFromLocalStorage","getCourseIDFromLocalStorage",this.retrieveTheQuiz()).subscribe(
           res =>{
             if(res.error == false){
              this.quiz = res.exam!;
               this.changeDetectorRef.detectChanges();
                console.log(this.quiz);
              }}
ngOnInit(){
this.loadQuiz();
}

in template:在模板中:

{{quiz.quizSetup?.quizTitle}}

I'm calling also detectChanges() and nothing happens the templatae is not updated !我也在调用detectChanges()并且没有任何事情发生,模板没有更新!

@Component({
    selector: 'app-selector',
    changeDetection: ChangeDetectionStrategy.OnPush,
    template: `...`
})

set changeDetection onPush for your componente, and then use inside the subscription how you already made.为您的组件设置 changeDetection onPush ,然后在订阅中使用您已经制作的方式。

or, you can use a boolean and ngIf inside your template:或者,您可以在模板中使用 boolean 和 ngIf:

loadData = false;

ngOnInit(): void {
  this.loadData = true;
  this.courseService.getExam().substribe(res => {
    // do stuff
    this.loadData = false; // set if to false when data is loaded
  });
}

template:模板:

<div *ngIf="!loadData">
  your content
</div>

this will force the page to be rendered again.这将强制页面再次呈现。 I prefer first option.我更喜欢第一个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM