我正在使用Angular6。
我正在从另一个服务(服务1)调用服务(服务2)getData
。服务2中的发布请求成功,并将数据打印到控制台。但是,数据不会返回给正在调用service2的service1,并且'result'对象始终是未定义的。
呼叫服务(service1)
this.service.getData(id, token).then(
result => {
console.log("result " + result);
},
error => {
console.log("error " + error);
});
服务(服务2)
getData(id, token): Promise < any > {
var startTime: number = new Date().getTime();
return new Promise < any > ((resolve, reject) => {
this.http.post(url, soapMessage, {
headers: new HttpHeaders().set('Content-Type', 'text/xml'),
responseType: 'text'
}).toPromise().then(
res => { // Success
resolve();
console.log(res);
//return res;
},
msg => { // Error
}
);
});
}
答案 0 :(得分:2)
您错过了通过res
的裁决:
.then(res => { // Success
resolve(res);
console.log(res);
//return res;
},
完全不确定为什么无缘无故地退还Promise。您的代码可以像这样被大量重构:
服务2:
getData(id, token): Promise < any > {
var startTime: number = new Date().getTime();
return this.http.post(url, soapMessage, {
headers: new HttpHeaders().set('Content-Type', 'text/xml'),
responseType: 'text'
});
}
服务1:
this.service.getData(id, token).subscribe(
result => {
console.log("result " + result);
},
error => {
console.log("error " + error);
});
答案 1 :(得分:0)
最好使用可观察的rxjs。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs';
import {Idata} from './Idata'
@Injectable()
export class ShareService {
constructor(private httpc:HttpClient)
{
}
public getPosts():Observable<Idata[]>
{
return this.httpc.get<Idata[]>('https://jsonplaceholder.typicode.com/posts');
}
}
//In your component subscribe to Observable<Idata[]> to get instance of Idata
public data:Array<Idata>=[];
constructor(public service:ShareService)
{
this.service.getPosts().subscribe(value => {
this.data=value;
});
}