3. angular lab assignment service
3. angular lab assignment service
Angular service
Angular services are task-based. Services are reusable code which shared among different
components. Angular provides built-in(HTTP, router, animation, form, UI Library,) and custom
services. services work on dependency injection mechanism.
Services may be written by just defining a typescript(with extension .service.ts) class with
decorator @Injectable annotation. Providers are used to declaring or injecting classes,
functions, and values by which they may be used by the dependency injection mechanism.
Services may be injected in different components, modules, and other services.
We need to crete a service with array of data containing hobbies and an method
hobbies = [
'dancing',
'singing',
'internet'
];
servicemethod(){
return 'Its just a simple service method';
}
Code:
@Injectable()
export class DataService {
// Create array
hobbies = [
'dancing',
'singing',
'internet'
];
constructor() { }
// Create simple angular service method
servicemethod(){
return 'Its just a simple service method';
}
Step 2: Update app.module.ts (Pass the reference to newly created service and add providers)
@Component({
selector: 'app-root',
template: `
<p>hi {{data}}</p>
<li *ngFor="let h of itemsarray">
<b> {{h}} </b>
</li>
`,
export
})
}providers:[DataService]
//
constructor(private
itemsarray=[]
data;
}this.itemsarray
//
this.data
Don't
String
useclass
property
method
forget
and
=AppComponent
this.dataservice.servicemethod();
array
to
of
of
=add
service
service
variable
this.dataservice.hobbies;
dataservice:
reference
declartion
{ ofDataService)
DataService{