Tuesday, November 29, 2016

Work with service in Angular2

Conceptually service is independent snippet of code which contains certain functionality or business logic. In Angular2 service is nothing but class of typescript (If we use typescript) which we can inject to component or module.

Yes, we can inject service to both component and module level. In this example we will demonstrate same.

If you are new in Angular2 , I will recommend to go through my previous article to setup angular2 project in IDE.


So, let’s start to implement one simple service which will return list of Person Object.
Add app.dataService.ts file in app folder. Here is content of file.

import {Injectable} from "@angular/core";
export interface Person {
    name: string
}

@Injectable()
export class dataService{
   
    getPerson(): Person[]
    {
        return [
            { name: "Ram" },
            { name: "Syam" },
            { name: "Jodu" }
        ];
    }
}

Here Person interface is type which we are returning from getPerson() function. Please note that the @Injectable decorator is needed when we want to inject to some other unit of code.

Inject service to component

As we said, service can be injectable both to component and module. Here we will inject service to component. Here we have created PersonComponent where we are injecting service in provider section.

import {Component} from '@angular/core';
import {dataService ,Person } from './app.dataservice'
import {OnInit} from "@angular/core";

@Component({
    selector: 'person',
    template: `<ul>
    <li *ngFor="let p of _persons">{{p.name}}</li>
    </ul>`,
    providers: [dataService],
})
export class PersonComponent {

    public _persons: Person[];
    constructor(private _dataService: dataService)
    {
        this._persons = this._dataService.getPerson();
    }

}


In constructor we are consuming getPerson() function which populating _Person member. Now, let’s create a view to display the component. Here is our sample view.

<!DOCTYPE html>
<html>

<head lang="en">
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
   
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
   
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
</head>

<body>
    <person>Loading App...</person>

</body>
</html>


Once we run the application ,we will see that data is showing like this.



Inject service in module

Now, let’s see how we can inject service to module. Here mainModule of application where we are injecting service in provider section.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PersonComponent } from './app.main_component';
import { dataService} from './app.dataservice';

@NgModule({
    imports: [BrowserModule ],
    declarations: [PersonComponent],
    bootstrap: [PersonComponent],
    providers: [dataService]
})
export class mainModule
{

};

Now, we can use the service in PersonComponent without inject it.

import {Component} from '@angular/core';
import {dataService, Person } from './app.dataservice'
import {OnInit} from "@angular/core";

@Component({
    selector: 'person',
    template: `<ul>
    <li *ngFor="let p of _persons">{{p.name}}</li>
    </ul>`
})
export class PersonComponent {

    public _persons: Person[];
    constructor(private _dataService: dataService) {

        this._persons = this._dataService.getPerson();
        console.log(JSON.stringify(this._persons));

    }

}

8 comments:

  1. please show me the code of operator overloading and function overloading in C# windows application



    ReplyDelete
  2. Hello @Anonymous, that's actually very good choice, you can keep same codebase for both Android and iOS.Are you interested in App Development With Angular then you must be looking for effective development team then you are at the right place for more details on it please go through the website.visit:

    ReplyDelete
  3. Hello @Anonymous, that's actually very good choiceAs Machine Learning & Artificial Intelligence Experts, we can help you inImplementing complex and highly beneficial algorithms that suits your business model. Our data scientists and AI developers will strategically formulate the algorithms depending on your dataset to overcome your core challenges and forthcoming opportunities.For more info on machine learning development servicesvisit:

    ReplyDelete
  4. We are an Android Application Development Company in the USA, providing android application development services for android devices with experienced android app developers.

    ReplyDelete
  5. Very beautifully explained nice blog buddy .Are you among one of those who are looking for Ios App Development Services then you are at right place we have dedicated development team who are expert in this so what are you waiting for just visit the official website or contact Us.

    ReplyDelete
  6. Very beautifully explained nice blog buddy .Are you among one of those who are looking for Hire Android App Developers then you are at right place we have dedicated development team who are expert in this so what are you waiting for just visit the official website or contact Us.

    ReplyDelete
  7. Very beautifully explained nice blog buddy.If you are looking for Flutter Mobile App Development t then you are at the right place Then you've come to the right place because we have a dedicated development team that is a specialist in this area. So, what are you waiting for? Visit the official website or email us.

    ReplyDelete