在函数调用get请求之前运行的Javascript警报

时间:2016-06-14 18:57:34

标签: angularjs typescript

private isValidURL(url: string) {
    var isValid = false;
    this.$http.get(url).then(
        (data) => {
            console.log('success');
            isValid = true;
        }
    ).catch( 
        (reason) => {
            console.log('failure ' + reason);
            isValid = false;
        }
    ).then(
        () => {
            return isValid;
        }
    )
}
private anotherFunc() {
    if (!this.isValidURL(url)) {
        alert('Wrong URL');
        return false;
    }
}

if语句中的警报正在isValidURL函数调用之前执行。如何确保首先执行该功能?

2 个答案:

答案 0 :(得分:0)

使用承诺。 console.log调用的长版本就是这个

private isValidURL(url: string) {
    return new Promise((resolve, reject) => {
        this.$http.get(url).then(
            (data) => {
                console.log('success');
                resolve();
            }
        ).catch(
            (reason) => {
                console.log('failure ' + reason);
                reject();
            }
        );
    }

private anotherFunc() {
    this.isValidURL(url).catch(){
        alert('Wrong URL');
        return false;
    }
}

或简短版本,只需使用$http返回的承诺

private isValidURL(url: string) {
    return this.$http.get(url);
}    
private anotherFunc() {
    this.isValidURL(url).catch(){
        alert('Wrong URL');
        return false;
    }
}

答案 1 :(得分:0)

不确定ts语法,但是像这样:

private isValidURL(url: string) {
  return this.$http.get(url)
    .then(() => true, () => false);
}
private anotherFunc() {
  this.isValidURL(url)
    .then(isValid => {
      console.log(isValid ? 'Valid' : 'Invalid');
    });
}