Answer the question
In order to leave comments, you need to log in
How to bind to data in a service?
Good afternoon! I am learning angular2. There is a service OrdersService.ts
function this.get(api.orders) loads data from the server.
@Injectable()
export class OrderService extends BasicService {
orders : OrderViewModel[] = [];
private
constructor(public http: Http, public notificationService: NotificationsService){
super(http,notificationService);
}
getOrders() : Observable<Array<models.OrderViewModel>> {
return this.get(api.orders);
}
}
export class MainComponent implements OnInit {
exportData: ExportModel[] = [];
orderData : OrderViewModel[];
constructor(config: NgbTabsetConfig, private orderService: OrderService, private exportService: ExportService) {
config.justify = "center";
config.type = "pills";
}
public options = {
position: ['top','right']
};
ngOnInit() {
this.orderService.getOrders().subscribe(r=>{
this.orderData = r;
});
this.exportService.getExports().subscribe(r=>{
this.exportData = r;
});
}
onPlacemarkSelected(data:any){
alert(data.length);
}
}
<div class="col-6">
<app-yamap [orderData] = "orderData" (placemarkSelection)="onPlacemarkSelected($event)"> </app-yamap>
</div>
Answer the question
In order to leave comments, you need to log in
In principle, this can be solved using BehaviorSubject:
export class MainComponent implements OnInit {
public orderData$ = new BehaviourSubject<OrderViewModel[]>([]);
ngOnInit() {
this.orderService.getOrders().subscribe(r=>{
this.orderData$.next(r);
});
}
}
export class YaMap implements OnInit {
@Input() orderData$: BehaviourSubject<OrderViewModel[]>;
public addOrder(newOrder: OrderViewModel) {
this.orderData$.next([...this.orderData$.getValue(), newOrder]);
}
}
<order-map-element *ngFor="let order of orderData$ | async">
{{ order.price }}
</order-map-element>
<button (click)="addOrder({price: 14.99})">Add another order</button>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question