使用Angular 2.我有一个组件和服务。在组件中,我请求获取公司列表。然后它调用服务以通过API获取公司。在响应时,公司存储在名为companies的服务变量中。另外,一个名为announceCompanyData()的observable被宣布。组件侦听事件并请求数据服务并刷新UI。
我觉得这是一种处理HTTP响应的复杂方法。在Angular 2中有更简单的方法吗?这是我的代码如下:
服务
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
SolidBrush brush = new SolidBrush(Color.Black);
g.FillRectangle(brush, 35, 30, 140, 420);
if (figure.Equals("red"))
{
brush.Color = Color.Red;
g.FillEllipse(brush, 35, 30, 140, 140);
figure = "red";
}
else if (figure.Equals("yellow"))
{
brush.Color = Color.Yellow;
g.FillEllipse(brush, 35, 170, 140, 140);
figure = "yellow";
}
else if (figure.Equals("green"))
{
brush.Color = Color.ForestGreen;
g.FillEllipse(brush, 35, 310, 140, 140);
figure = "green";
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (figure.Equals("red"))
{
System.Threading.Thread.Sleep(750);
figure = "yellow";
Invalidate();
System.Threading.Thread.Sleep(750);
figure = "green";
Invalidate();
}
else if (figure.Equals("green"))
{
System.Threading.Thread.Sleep(750);
figure = "yellow";
Invalidate();
System.Threading.Thread.Sleep(750);
figure = "red";
Invalidate();
}
}
组件
{{1}}
答案 0 :(得分:1)
不是每次都向订阅observable的所有组件宣布,你只需声明一个服务类型为observable的方法,并在组件中订阅此方法,这样每当你在完成请求后调用getCompanies方法它将返回组件数据
在服务中
preferredLanguages
在组件
中getCompanies() (): Observable<Companies[]> {
return this.http.get(this.heroesUrl).map(this.extractData)
}
private extractData(res: Response) {
if(res.status < 200 || res.status >= 300) {
throw new Error('Bad response status ' + res.status);
}
let body = res.json();
/* here you can save body in any global variable*/
return body.data || {};
}