Answer the question
In order to leave comments, you need to log in
Angular 2 services?
I'm studying Angular 2 not so long ago and the question arose of how to call the service I need.
There is a service:
@Injectable()
export class TaskService {
httpAdress: string;
constructor(private http: Http) {
this.httpAdress= 'http://localhost:8080';
}
getByType(id: number){
let headers = new Headers();
headers.append('Authorization', 'Bearer '+ JSON.parse(localStorage.getItem('token')).access_token);
return this.http.get(this.httpAdress+'/api/task/type/' + id,{headers: headers}).map((response: Response) => response.json());
}
export class TasksComponent implements OnInit{
model: any = {};
type: any;
id: number;
constructor(
private taskService: TaskService,
private router:Router){}
ngOnInit()
{
this.type = this.taskService.getByType(this.id);
}
}
}
<p>{{type}}</p>
this.taskService.getByType().subscribe(type => {
this.type = type;
},
err => {
console.log(err);
return false;
});
It didn't work either. Answer the question
In order to leave comments, you need to log in
getByType
returns an Observable (read about RxJs).
In your case, in the class where the service is used, you need to do this:
export class TasksComponent implements OnInit {
model: any = {};
type: any;
id: number;
constructor(
private taskService: TaskService,
private router: Router
) {}
ngOnInit() {
this.type = this.taskService.getByType(this.id).subscribe((type) => {
this.type = type;
});
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question