S
S
Serp3nt2017-04-11 19:55:23
JavaScript
Serp3nt, 2017-04-11 19:55:23

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());
    }

So I call it in the component:
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);

    }
}
    }

I write in the html file As a result, I see the output [object Object] I also tried:
<p>{{type}}</p>
this.taskService.getByType().subscribe(type => {
      this.type = type;
    },
    err => {
      console.log(err);
      return false;
    });
It didn't work either.
What am I doing wrong? I ask for your help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sanex3339, 2017-04-11
@sanex3339

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 question

Ask a Question

731 491 924 answers to any question