services/my.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
data: any = [1, 2, 3];
getData() {
return Promise.resolve(this.data);
}
}
getData()
now acts likes a REST call that creates a Promise, which gets resolved immediately. The results can be handheld inside .then()
and errors can also be detected. This is good practice and convention for asynchronous methods.
components/my.component.ts
import { Component, OnInit } from '@angular/core';
import { MyService } from '../services/my.service';
@Component({...})
export class MyComponent implements OnInit {
data: any[];
// Creates private variable myService to use, of type MyService
constructor(private myService: MyService) { }
ngOnInit() {
// Uses an "arrow" function to set data
this.myService.getData().then(data => this.data = data);
}
}