angular2 在ngOnInit() 中初始化数据时页面上没有相应UI的变化

 @Component({
   selector: 'app-home',
   templateUrl: './home.component.html',
   styleUrls: ['./home.component.scss'],
   providers: [ QuestionService ]
 })
 export class HomeComponent implements OnInit {
   constructor(
     private questionService: QuestionService,
     private router: Router
   ) { }

  questions = []
  title = 'old'

  ngOnInit(): void {
    this.getQuestions();
  }

  getQuestions(): void {
    this.questionService.getQuestions()
      .then(questions => this.questions = questions)
      .catch((error) => {
        console.error(error);
    });
 }

对应的模板

{{ title }}
<ul class="q-container">
  <li *ngFor="let question of questions"
   class="question-card">
  {{ question.content }}
 </li>
</ul>

理应在页面上显示question.content 但是没有显示。。这是为什么?

但是如果这样写

@Component({
   selector: 'app-home',
   templateUrl: './home.component.html',
   styleUrls: ['./home.component.scss'],
   providers: [ QuestionService ]
 })
 export class HomeComponent implements OnInit {
   constructor(
     private questionService: QuestionService,
     private router: Router
   ) { }

  questions = []
  title = 'old'

  ngOnInit(): void {
    this.getQuestions();
  }

  getQuestions(): void {
    this.questionService.getQuestions()
      .then(questions => this.questions = questions)
      .catch((error) => {
        console.error(error);
    });
    setTimeout(() => {
      this.title = 'new';
    }, 1000);
 }

又正常显示question.content了。这是为什么?

阅读 5.2k
1 个回答

目测是你的服务部分写错了,贴出来看看?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题