我在从方法中返回值时遇到问题,该值始终是未定义的,并且Promise仅在方法返回后才产生该值。
我已尝试观察到但未获得预期的结果。
import { Router } from "@angular/router";
import { JwtHelperService } from "@auth0/angular-jwt";
import { HttpClient } from "@angular/common/http";
import { map } from "rxjs/operators";
import { BehaviorSubject, Observable, of, Subject } from "rxjs";
interface ServerStatus {
status: string;
}
interface BaseApi {
baseURL: string;
apiURL: string;
}
const helper = new JwtHelperService();
@Injectable({
providedIn: "root"
})
export class AuthService {
public token: string = "";
public api: string;
constructor(
private httpService: HttpClient,
private router: Router
) {
}
public decodedToken: JSON;
public role: string;
public timersubscribe: any;
public myDate: Date;
public stage: number;
public tmp: any;
getStage() {
let url ;
this.getApi().then(ret => url = ret))
//this will appear only after the return is done
console.log(url);
//the url is always undefined
return this.httpService.get<ServerStatus>(url);
}
getApi() {
return this.httpService.get<BaseApi>("../../assets/api.json").toPromise().then(result => {
return result.apiURL;
})
}
}
我希望在方法(getStage())返回之前将承诺解析为字符串。
答案 0 :(得分:0)
您可以使用async await
async getStage() {
let url = await this.getApi();
//this will appear only after the return is done
console.log(url);
//the url is always undefined
return this.httpService.get<ServerStatus>(url);
}
答案 1 :(得分:0)
您好,您的问题是如何解决并兑现诺言。尝试此操作:
getStage() {
return new Promise<string>((resolve,reject)=>{
let url ;
this.getApi().then(ret => {
url = ret
//this will appear only after the return is done
console.log(url);
//the url is always undefined
this.httpService.get<ServerStatus>(url).then((res)=>{
resolve(res)
});
})
}
getApi() {
return new Promise<string>((resolve,reject)=>{
this.httpService.get<BaseApi>("../../assets/api.json").toPromise().then(result => {
resolve( result.apiURL);
})
})
}
答案 2 :(得分:0)
您无法从Promise中收到纯字符串-Promise是异步的,因此您必须异步处理它。在js中,没有像“等待诺言”这样的方法
我会说做类似的事情:
getStage(): Promise<any> {
return this.getApi().then(url => {
return this.httpService.get<ServerStatus >(url).toPromise();
});
}
在这里,您从getStage返回了Promise,在这里您还可以返回可观察到的(如:)。
getStage(): Observable<any> {
return this.getApi().then(url => {
return this.httpService.get<ServerStatus >(url);
});
}
但是,别忘了订阅;)
getStage().subscribe(...);
答案 3 :(得分:0)
使用
之类的异步等待功能async getStage(){ 让url =等待this.getApi();
//url won't be undefined here
return this.httpService.get<ServerStatus>(url);
}