【问题标题】:Module not reloading after JSON.parse errorJSON.parse 错误后模块未重新加载
【发布时间】:2017-07-30 22:12:12
【问题描述】:

我有一个 QA 测试页面,我们的 QA 可以通过将 json 传递给模拟服务来复制服务器的行为。 当我使用有效的 json 时,一切都按预期工作,但是当我使用无效的 json 时,我收到一个错误,这是正常的。我遇到的问题是该 json 错误后页面不再更新,即使使用有效的 json。

这里是测试页组件的摘录:

export class QaTestComponent implements OnInit {
  modules: Module[];
  pageState: PageState;
  mockModulesValue: string;
  mockPageStateValue: string;

  constructor(private moduleService: MockModuleService, private pageStateService: MockPageStateService) { }

  getModules() {
    this.moduleService.getModules().then(modules => this.modules = modules);
  }

  updateModules() {
    let jsonModules = JSON.parse(this.mockModulesValue);
    this.moduleService.setModules(jsonModules);
    this.getModules();
  }

这是带有函数调用的html文件:

  <div class="qa-test-interface-setup-datas-type col-md-6">
    <h3 class="qa-test-interface-setup-datas-type-title">Modules</h3>
    <textarea name="" id="" cols="30" rows="10" class="qa-test-interface-setup-datas-type-textarea" [(ngModel)]="mockModulesValue"></textarea>
    <button class="qa-test-interface-setup-datas-type-button" (click)="updateModules()">Update</button>
  </div>

这是模拟服务:

export class MockModuleService implements ModuleService {
  raw: Module[] = aJsonArray;
  response: Module[] = this.raw;

  setModules(mockModules: Module[]) {
    this.response = mockModules == null ? this.raw : mockModules;
  }

  getModules(): Promise<Module[]> {
    return Promise.resolve(this.response);
  }
}

我尝试记录以查看一个有效的 mockModuleValues 是否在发生错误后在组件或服务中被阻止,但我可以看到它一直持续到 getModules()。

【问题讨论】:

    标签: javascript angularjs json angular ecmascript-6


    【解决方案1】:

    所以经过一些研究后,我开始在 try/catch 中进行 json 解析以避免错误杀死我的订阅者。

       updateModules() {    
         if(this.mockModulesValue) {
            try {
              let jsonModules = JSON.parse(this.mockModulesValue);
              this.moduleService.setModules(jsonModules);
              this.getModules();
            } catch(e) {
              alert(e);
            }
         }
       }
    

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多