Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Angular 2 service


May 08, 2021 Angular2


Table of contents


Describe

A service is a JavaScript function that is only responsible for performing specific tasks. A ngle services are injected using a dependency injection mechanism and include the values, functions, or attributes required by the application. There are no services in Angular, and there is no ServiceBase class, but services can still be used as the basis for Angular applications.

Example

The following example describes the use of services in Angle 2:

<!DOCTYPE html>
<html>
  <head>
    <title>Angular 2 Services</title>
    <!--Load libraries -->
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/es6-shim.min.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system-polyfills.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2-polyfills.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/typescript.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/Rx.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2.dev.js"></script>
    <script>
      System.config({
        transpiler: 'typescript',

        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}}
      });
      System.import('/angular2/src/app/service_main')
            .then(null, console.error.bind(console));
    </script>
  </head>
<body>
   <my-app>Loading...</my-app>
</body>
</html>

The above code includes the following configuration options:

  • You can configure index files using the .html version. SystemJS converts TypeScript to JavaScript before running the application using the transpiler option.

  • If you don't translate to JavaScript before you run your application, you may see compiler warnings and errors hidden in your browser.

  • TypeScript generates metadata for each class of your code when you set the emitDecorator Metadata option. If you do not specify this option, a large amount of unused metadata is generated, which affects the file size and the application runtime.

  • Angular 2 includes packages from the app folder, Chinese will have a .ts extension.

  • Next it loads the main component file from the application folder. If the primary component file is not found, it displays an error in the console.

  • When Angula called the boot function in main.ts, it reads the Company metadata, finds the "app" selector, finds an element label named app, and loads the application between those tags.

To run the code, you need the following TypeScript (.ts) file, which you need to save under the application folder.

metadata_main.ts
import {bootstrap} from 'angular2/platform/browser';     //importing bootstrap function
import {AppComponent} from "./app_service.component";    //importing component function

bootstrap(AppComponent);

Now we're going to create a component in the TypeScript (.ts) file, and we're going to create a view of that component.

app_service.component.ts
import {Component} from 'angular2/core';
import {MyListComponent} from "./service-list.component";

@Component({
    selector: 'my-app',
    template: `
    <country-list></country-list>
    `,
    directives: [MyListComponent]
})
export class AppComponent {
}
  • @Component is an decorator that uses configuration objects to create components and their views.

  • The selector creates an instance of the component and finds the tag in the parent HTML.

  • Next we create an instruction called MyListComponent, which will be accessed from the service-list.component file.

service-list.component.ts
import {Component} from "angular2/core";
import {CountryService} from "./country.service";
import {Contact} from "./country";
import {OnInit} from "angular2/core";

@Component({
   selector: "country-list",
   template: ` List of Countries<br>
   <ul>
      <li *ngFor="#cntry of countries">{{ cntry.name }}</li>
   </ul>
   `,
   providers: [CountryService]
})

export class MyListComponent implements OnInit {
   public countries : Country[];
   constructor(private _countryService: CountryService) {}

   getContacts(){
      this._countryService.getContacts().then((countries: Country[]) => this.countries = countries);
   }

ngOnInit():any{
   this.getContacts();
}
}
  • The local variable cntry can be referenced in the template and get an index of the array. Angular 2 will use the template's local variables to bind the model name from the array.

  • We have a resource called a provider that registers classes, functions, or values in the context of dependency injection. You can inject a service called CountyService @Inj using the ectable() in the country.service.ts file.

  • Next you use the OnInit hook to implement in the MyListComponent class, which indicates that Angular created the component. Use constructor calls to _countryService and populate the list of countries.

  • When you create a component and evaluate the input, call the ngOnInit() hook.

country.service.ts
import {Injectable} from "angular2/core";
import {COUNTRIES} from "./country.contacts";

//@Injectable() specifies class is available to an injector for instantiation and an injector will display an error when trying to instantiate a class that is not marked as @Injectable()

@Injectable()

//CountryService exposes the getContacts() method that returns the data
export class CountryService {
   getContacts() {
      return Promise.resolve(COUNTRIES); // takes values from country.contacts typescript file
   }
}
country.contacts.ts
import {Country} from "./country";

//storing array of data in Country
export const COUNTRIES: Country[] =[
   {name :"India"},
   {name: "Srilanka"},
   {name: "South Africa"},
   {name: "New Zealand"}
];
country.ts
export interface Country{
   name: string
}

Output

Let's take the following steps to see how the code above works:

  • Save the HTML code above as an index.html file, as we created in the Environment chapter, and use the app i.gt; folder above, which contains the .ts file.

  • Open the terminal window and enter the following command:

    npm start
  • Later, the browser tab should open and display the output, as shown below.

Or , you can run this file in other ways:

  • Save the HTML code above as a file in the server root angular2_services.html folder.

  • Open this HTML file as http://localhost/angular2_services.html and display the output shown below.