Javascript 如何在单击按钮时刷新角度服务?
当我第一次打开它时,我在模式中填充了数据,因此,在保存更改后,我清空了Javascript 如何在单击按钮时刷新角度服务?,javascript,angular,typescript,Javascript,Angular,Typescript,当我第一次打开它时,我在模式中填充了数据,因此,在保存更改后,我清空了questions数组。现在,当我再次打开modal时,我只看到最后一个问题,而不是新数据,因为我在openModal上再次调用服务时,它应该会获得新数据或为null。我不确定questions为什么仍然包含最后一个元素。有什么想法吗 我想清空这个。当我打开modal时,提问数组并再次调用getData服务 app.component.ts import { Component } from '@angular/core
questions
数组。现在,当我再次打开modal时,我只看到最后一个问题,而不是新数据,因为我在openModal
上再次调用服务时,它应该会获得新数据或为null。我不确定questions
为什么仍然包含最后一个元素。有什么想法吗
我想清空这个。当我打开modal时,提问数组并再次调用getData
服务
app.component.ts
import { Component } from '@angular/core';
import { ApiService } from './api.service';
import { isGeneratedFile } from '@angular/compiler/src/aot/util';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
data: any;
questions: any[] = [];
singleQuestion: any[] = [];
showSaveButton: boolean = false;
showNextButton: boolean = true
constructor(private dataService:ApiService) {}
openModal(){
this.questions = this.dataService.getData();
console.log('question modal', this.questions);
if(this.questions.length){
this.startFormatting();
}
}
startFormatting() {
this.showNextButton = true;
this.singleQuestion = this.questions[0];
this.showSaveButton = false;
}
getNextQuestion(e: object){
this.questions.shift();
if(this.questions.length > 0){
this.singleQuestion = this.questions[0];
if(this.questions.length === 1) {
this.showNextButton = false;
this.showSaveButton = true;
}
}
}
saveChanges(){
this.questions = [];
this.singleQuestion = [];
}
}
api.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private data: any;
private questions: any[];
constructor() { }
getData () {
return this.data;
}
setData (_data:any) {
this.data = _data;
}
}
在清除值之前,只需将服务中的数据保存在方法“saveChanges()”中
试一试
你能为同样的模式创建一个stackblitz吗?当模式再次打开时,不会导致没有问题被加载吗?(++我没有看到OP在服务中设置值的任何地方。)this.dataService.setData(this.questions);此行设置服务中的日期值。
saveChanges() {
this.dataService.setData(this.questions);
this.questions = [];
this.singleQuestion = [];
}