2017-03-09 16 views
0

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

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

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()。

回答

0

因此,经过一番研究,我发现我在try/catch中执行了json解析,以避免错误导致我的订阅者无法访问。

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