17.10.2018 Views

Angular

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

components/my.component.ts<br />

Alternative approach to register application providers in application components. If we add providers at component<br />

level whenever the component is rendered it will create a new instance of the service.<br />

import { Component, OnInit } from '@angular/core';<br />

import { MyService } from '../services/my.service';<br />

@Component({<br />

...<br />

...<br />

providers:[MyService] //<br />

})<br />

export class MyComponent implements OnInit {<br />

data: any[];<br />

// Creates private variable myService to use, of type MyService<br />

constructor(private myService: MyService) { }<br />

}<br />

ngOnInit() {<br />

this.data = this.myService.getData();<br />

}<br />

Section 23.2: Example with Promise.resolve<br />

services/my.service.ts<br />

import { Injectable } from '@angular/core';<br />

@Injectable()<br />

export class MyService {<br />

data: any = [1, 2, 3];<br />

}<br />

getData() {<br />

return Promise.resolve(this.data);<br />

}<br />

getData() now acts likes a REST call that creates a Promise, which gets resolved immediately. The results can be<br />

handheld inside .then() and errors can also be detected. This is good practice and convention for asynchronous<br />

methods.<br />

components/my.component.ts<br />

import { Component, OnInit } from '@angular/core';<br />

import { MyService } from '../services/my.service';<br />

@Component({...})<br />

export class MyComponent implements OnInit {<br />

data: any[];<br />

// Creates private variable myService to use, of type MyService<br />

constructor(private myService: MyService) { }<br />

}<br />

ngOnInit() {<br />

// Uses an "arrow" function to set data<br />

this.myService.getData().then(data => this.data = data);<br />

}<br />

GoalKicker.com – <strong>Angular</strong> 2 Notes for Professionals 99

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!