你需要 return 来自的承诺 startFunction :
return
startFunction
startFunction(entry) { return this.storage.get('subdomain').then(result => { // ^^^^^^ return this.http.post(result + this.apiUrl, JSON.stringify(entry), { headers: HEADER.headers}; }); }
然后使用 then 代替 subscribe :
then
subscribe
otherFunction(){ this.GetApi.startFunction(entry).then(result => { console.log(result) }, err => { console.log(err); }); }
@Bergi答案是对的。但是你需要在承诺的解决之后订阅,因为你的promise会返回一个observable:
startFunction(entry) { return this.storage .get('subdomain') .then(result => this.http.post(result + this.apiUrl, JSON.stringify(entry), { headers: HEADER.headers}); }
和:
otherFunction(){ this.GetApi.startFunction(entry) .then( observable$ => observable$.subscribe( result => { console.log(result) }, err => { console.log(err); })) }
我会利用一个 HttpInterceptor 这里是为了避免获取所有http请求的子域。 HttpInterceptor很棒! :d
HttpInterceptor
那么你可以做什么,创建一个拦截器,正如你在问题中所说的那样,你在发出任何http请求之前设置子域,所以假设在你发出http请求时总是有一个子域。
另外我看到你正在设置标题。如果所有标题都相同,您也可以在拦截器中执行此操作。我不是在这里包括它。
所以这就是你的拦截器的样子:
@Injectable() export class NoopInterceptor implements HttpInterceptor { constructor(private storage: Storage) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const obs = Observable.fromPromise(this.storage.get('subdomain')); return obs.flatMap(data => { console.log(data); // here should be your subdomain // add your subdomain, and the rest of the url const apiReq = req.clone({ url: `${data}${req.url}` }); return next.handle(apiReq); }) } }
这意味着,在您的请求中,忽略子域,并添加后一个URL的一部分,因为我们在拦截器中添加子域:
return this.http.post(this.apiUrl, entry, { headers: HEADER.headers}
这是一个虚拟示例,我只是在拦截器中的存储中设置数据,你可以在你当前正在做的那样做。
请注意,您不需要对有效负载进行字符串化。