【问题标题】:If the file doesn't exist, how can I point to another?如果该文件不存在,我该如何指向另一个文件?
【发布时间】:2018-10-05 22:05:14
【问题描述】:

我正在使用 Angular 6,我正在尝试检查 _appconfig.json 文件是否存在于根目录中。如果该文件不存在,我想将 http.get() 调用指向另一个 URL。不过,我似乎无法让事情表现得像我想要的那样,并且想知道是否有人可以在这里帮助我。

如果所述文件不存在,我该怎么更改 URL?

configUrl = "_appconfig.json"; 

  constructor(private http: HttpClient) {}

  data: any;

  getConfig(): Promise<configType> {
    return this.http
      .get(this.configUrl)
      .toPromise()
      .then(response => response as configType)
      .catch(this.handleError);
  }

对于它的价值,如果文件确实存在,这将按预期运行。

【问题讨论】:

标签: angular typescript promise httpclient


【解决方案1】:

这可能是一个可以帮助您的解决方案。 重要的是捕获错误,如果错误恰好是 404 错误,您可以确定该文件未找到。

我建议您使用 oberservables 而不是 Promise,但它们也应该以类似的方式工作。

这是一个我尝试加载“test.txt”的示例,如果找不到该文件,我将加载 second.json。

private loadMainFile() {
    this.httpClient.get('/asset/test.txt').subscribe(() => {
      // HANDLE file found
    }, (err) => {
      // HANDLE file not found
      if (err.status === 404) {
        this.loadSecondFile();
      }
    });
  }

  private loadSecondFile() {
    this.httpClient.get('/asset/second.json').subscribe(() => {
      // HANDLE file found
    }, () => {
      // HANDLE file not found

    });
  }

【讨论】:

    猜你喜欢
    • 2019-08-02
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2012-03-01
    • 2020-04-14
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    相关资源
    最近更新 更多