My Blog

Menu

Create Services

Posted: November 24, 2021. | By: Admin

In angular2 we are using services to interact with the server using API calls.

  • Get is used to get the data from server single user data (ex. Based on ID’s) and all user’s data.
get(url: string, options?: RequestOptionsArgs)
  • Post is used to post the newly created user’s form data to server.
post(url: string, body: any, options?: RequestOptionsArgs)
  • Put is used for send updated data of user and it is used for delete the selected user data from the list.
put(url: string, body: any, options?: RequestOptionsArgs)
  • The Injectable decorator is imported from the angular/core module.
  • We are creating a class called appService that is decorated with the Injectable decorator.

The @Injectable() decorator is needed when a Service needs dependencies injected to its constructor.

Example:

user.service.ts

import{Injectable} from '@angular/core';

import {Http, Response}from '@angular/http';

import 'rxjs/add/operator/map';

@Injectable()

export class UserService{

constructor(

private http:Http

){}

getUser(){

return this.http.get(`https://conduit.productionready.io/api/profiles/eric`)

.map((res:Response)=>res.json());

}

}

Users-list.component.ts

Import { Component } from '@angular/core';

Import { UserService } from './shared/index';

@Component({

selector: 'home-page',

template:` Load profile {{ profile | json }}  `

});

export class HomeComponent{

Profile: any;

constructor(private userService:UserService){

}

loadUser(){

this.userService.getUser().subscribe(data=>this.profile=data);

}

}

Note:

If you want to call Service from your component you must import that service class into component.ts page and imported service class name should be define in constructor to utilize the service in your page and also import Service class name into modules.ts page and define that service name in providers array.

About

Aapthi Technologies,Hyderabad offers a complete range of web solutions including web designing, developing, web hosting, Internet marketing and many more. With our electrifying presence, we have swirled the scenario of web solutions. We consistently invigorate our skill-set and tech-expertise and work with a high-level of integrity. Our keen-eye on emerging trends of online business as well as technical spheres has empowered us to render the most innovative solutions. Persistent development is the key drive of Aapthi Technologies, be it in terms of infrastructure, skill-set or technology. Team Aapthi Technologies, is fully committed to render back hundred percent value for the money paid by client.

Social Links

Our Bunker

Plot No -596, Near Reliance Fresh,
Vivekananda nagar colony, Kukatpally,
Hyderabad - 500072, India.