我的角度组件从注入的服务中获取数据......服务如下所示:
//method inside Customer-Service
getCustomers(): Observable <ICustomer> {
return this.http.get('http://foo.com/_api/app/Customers')
.map( (response: Response) => { return <ICustomer[]> response.json(); })
.catch(this.handleError)
}
&#13;
在我的组件中,我创建了这样的订阅......
export class CustomerComponent implements OnInit {
allCustomers: ICustomer[]
constructor(private fb: FormBuilder, private _custSvc: CustomerService ) { }
ngOnInit(): void {
this._custSvc.getCustomers().subscribe(customers => { this.allCustomers = customers },
(err) => console.log('something went wrong'),
() => { console.log('yep... its done.') })
//other methods below need allCustomers to be populated.
doSomething()
doSomethingElse()
}
&#13;
我希望doSomething和doSomethingElse方法等到allCustomers都有数据。人们如何在Angular中解决这个问题?
答案 0 :(得分:2)
提到@ jonrsharpe时,您需要在订阅的next
事件中调用doSomething()和doSomethingElse()函数。代码如下所示。
ngOnInit(): void {
this._custSvc.getCustomers()
.subscribe((customers) => {
this.allCustomers = customers;
// Call the functions here:
doSomething();
doSomethingElse();
},
(err) => console.log('something went wrong'),
() => { console.log('yep... its done.') })
};
}
当填充客户数据时,还有其他方法可以使函数调用执行,但这是最明显和最合乎逻辑的方式,并且将是您大多数时间所需要的。