Angular framework provides dependency injection to automatically inject services. Whenever we specify a service as a constructor parameter ,Angular automatically injects the service instance in the class.You provide required services to the different components using constructor parameters.
In Angular a service is a class decorated with the @Injectable decorator:
import { Injectable } from '@angular/core';
@Injectable()
export class MockService {
constructor() {
}
}
You can consume the declared service in your component as:
import { mock-service} from 'app/services/mock-service.service';
@NgModule({
declarations: [AppComponent]
imports: [BrowserModule],
providers: [MockService],
bootstrap: [AppComponent]
})
Though theoretically you can use any logic in you service ,it is common to implement data access logic in service. Then you can inject service in your constructor class as:-
constructor (private http: HttpClient) {}
getStudents() : Observable<Student[]> {
return this.http.get(this.studentsUrl )
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
Leave a Reply