我正在尝试使用subscribe方法从服务返回数据。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class DevRequestService {
constructor(private http: HttpClient){}
getListOfAgencies() {
return this.http.get('https://example.com/api/agency').subscribe(data => {
return data;
});
}
}
组件:
ngOnInit(): void {
console.log(this.devRequestService.getListOfAgencies());
}
下面是我在console.log中获得的输出,而不是使用值返回对象:
Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}
答案 0 :(得分:5)
您应该订阅数据并将其分配给组件中的变量,如下所示:
SELECT
business_id_fk,business_name,
total,
crude,
unassigned,
delivered,
cancelled,
postponed,
Estimated_Revenue,
Generated_Revenue,
TotalPrice,
Totaldelivered,
Totalorders,
ifnull(((TotalPrice / TotalQuantity)*100),0) AS 'sla_adherence',
ifnull(((Totaldelivered / Totalorders)*100),0) AS 'strike_rate'
FROM
(
SELECT
business_id_fk,business_name,
IFNULL(count(orderid_customer),0) AS total,
IFNULL(sum(CASE WHEN order_status IN ('CRD') THEN 1 ELSE 0 END), 0) AS crude,
IFNULL(sum(CASE WHEN order_status IN ('UNA') THEN 1 ELSE 0 END), 0) AS unassigned,
IFNULL(sum(CASE WHEN order_status IN ('DEL' , 'MCP' , 'CMP') THEN 1 ELSE 0 END), 0) AS delivered,
IFNULL(sum(CASE WHEN order_status IN ('CNL') THEN 1 ELSE 0 END), 0) AS cancelled,
IFNULL(sum(CASE WHEN order_status IN ( 'CAP' , 'CAD' , 'RSP' , 'RSD') THEN 1 ELSE 0 END), 0) AS postponed,
IFNULL(SUM(total), 0) AS 'Estimated_Revenue',
IFNULL(SUM(CASE WHEN order_status IN ('DEL' , 'MCP', 'CMP') THEN total ELSE 0 END), 0) AS 'Generated_Revenue',
sum(sla_del_datetime > delivery_datetime) AS TotalPrice,
sum(order_status in('DEL','MCP','CMP')) AS TotalQuantity,
sum(order_status in('DEL','MCP','CMP')) AS Totaldelivered,
count(*) AS Totalorders
FROM view_orders
where order_datetime between '2017-08-01 00:00:00' and '2017-10-17 23:59:59'
and parent_id IS NULL
GROUP BY business_id_fk
) AS A
ORDER BY total DESC;
答案 1 :(得分:1)
我会在你的.ts中这样做: 私人数据$:Observable;
ngOnInit(): void {
this.data$ = this.devRequestService.getListOfAgencies();
}
在你的.html模板中,这个:
<div> {{ data$ | async }} </div>
以获得价值。
答案 2 :(得分:0)
如果要加载要查看的数据,则应在服务中使用新主题。例如:
export class PostService {
subject = new Subject();
constructor(private httpClient: HttpClient) {}
const httpRequest = new HttpRequest(
'GET',
'/your-url',
body,
{
headers: new HttpHeaders().set('Content-Type', 'body'),
}
);
this.httpClient.request(httpRequest).subscribe((res) => {
if (res.type) {
this.subject.next(res.body);
}
});
return this.subject;
}
在组件中:
export class PostsComponent implements OnInit {
posts: any;
constructor(private postService: PostService) { }
ngOnInit() {
this.getPosts();
}
private getPosts() {
this.posts = this.postService.getPosts();
}
}
在视图中:
<app-post-item
class="col-md-4"
*ngFor="let post of posts | async"
[post]="post">
</app-post-item>
答案 3 :(得分:0)
我也遇到了这个问题,我没有得到响应,而是一个订户实例。事实证明,服务器代码未返回JSON可分析的响应。好像是一个无声的错误,不确定为什么。但是,当我修复服务器代码以返回对象时,得到了响应。