2

I am using Angular 6, and I'm trying to check if the _appconfig.json file exists at root. If the file doesn't exist, I want to point the http.get() call to another URL. I can't seem to get things to behave like I want, though, and was wondering if someone could help me here.

What could I do change the URL if said file doesn't exist?

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);
  }

For what it's worth, this behaves as expected in the event that the file does exist.

1 Answers1

4

Here might be a solution which helps you. The important thing is to catch the error and if the error happens to be a 404 error you can be sure, that the file wasn't found.

I recommend you to work with oberservables instead of promises but they should also work in a similar way.

Here an example where I try to load "test.txt" and if the file isn't found I will load 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

    });
  }
DaniS
  • 3,429
  • 1
  • 12
  • 18