Angular2: check file existance with http.get

2020-04-21 03:24发布

问题:

I have a simple method to check if a *.mp3 file in my local machine exists or not. It is supposed to return the status of the response (200, 404,403,etc), but it doesn't work.

fileExists(url){
        return this.http.get(url).timeout(2000)
                                 .map(res=>res.json())
                                 .subscribe(
                                           res=>{
                                                 console.log("res is");
                                                 console.log(res.status)
                                                 return res.status;},
                                           err =>{ 
                                                  console.log("Error is");
                                                   console.log(err.status); 
                                                   return err.status});

  }

I set a timeout for 2 seconds for it, however it only needs to check a file in my localhost. Therefore, i think, it has enough time to find the file.

it returns always:

Subscriber {closed: false, syncErrorValue: null, syncErrorThrown: false, syncErrorThrowable: false, isStopped: false…}

回答1:

If you want to compose an observable that emits the status code of a GET request, you can do this:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

this.http.get("/some-file.txt")
    .map((response) => response.status)
    .catch((error) => Observable.of(error.status || 404))
    .subscribe((status) => console.log(`status = ${status}`));

And if you want to more efficiently determine the existence of a file based on a HTTP status code, you could use the HEAD method, which won't retrieve the file's content:

this.http.head("/some-file.txt")
    .map((response) => response.status)
    .catch((error) => Observable.of(error.status || 404))
    .subscribe((status) => console.log(`status = ${status}`));

The problem with the code in your question is that you are looking for JSON content in the response and are looking for the status within that content. The status is in the response itself.

However, to implement a function that determines file existence, you don't even need to examine the status:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/mapTo';
import 'rxjs/add/operator/toPromise';

getFileStatus(path: string): Promise<boolean> {
    return this.http.head(path)
        .mapTo(true)
        .catch((error) => Observable.of(false))
        .toPromise();
}


标签: angular