我必须从角度服务调用组件中的函数。
我该怎么做?
在成功调用Web服务后,我想在组件中调用一个函数
答案 0 :(得分:1)
以下是步骤:
因此您可以按照以下过程将服务功能调用到组件。
Example:-
component file
==============
import { CustomerService } from './../../service/customer.service';
@Component({
templateUrl: 'add_additional_contact.html'
})
export class AddAdditionalContactComponent implements OnInit {
constructor(
private addcontactservice: CustomerService
) {}
ngOninit(){
this.addcontactservice.getCustomerList().subscribe((result) => {});
}
}
service file
==================
import { ErrorHandler, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { StaticData } from './../../common/static_data.service';
import { Router } from "@angular/router";
import 'rxjs/add/operator/toPromise';
@Injectable()
export class CustomerService {
public apiUrl = "api URL";
constructor(
private http: HttpClient
) { }
getCustomerList(): Observable<any> {
return this.http.post(this.apiUrl + 'addEditCustomerContact', { action: 'list' });
}
}
答案 1 :(得分:1)
我们可以轻松地从注入的服务中调用组件的功能
看看这个stackblidtz example,其中从服务中调用函数showAlert
我们订阅并获得结果的:
import { Component } from '@angular/core';
import { IProduct } from './product';
import { ProductService } from './products.service';
import { Http , Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Component ({
selector: 'my-app',
template: '<table border="1"><tr *ngFor="let elem of iproducts"><td>{{ elem.ProductID }}</td><td>{{ elem.ProductName }}</td></tr></table>',
providers: [ProductService]
})
export class AppComponent {
iproducts: IProduct[];
constructor(private _product: ProductService) {
}
ngOnInit() : void {
this._product.getproducts()
.subscribe( (iproducts) => {
this.iproducts = iproducts;
this.showAlert(); //call showAlert function <------
});
}
showAlert() {
console.log('we have the products !');
}
}
注意:服务的意图是注入到组件中,以便我们可以使用它并在其中使用所有业务逻辑,而不要将组件导入服务中,并且调用服务中组件的方法