I have created an interface and a service in which this service is responsible for getting some data from API but when I try to call that from a component, it returns undefined to me. these are my services and my component (I have also noticed that the function within the service returns void and I have provided them in app.module )
@Injectable()
export class TasksService {
compeletedTasks: Task[]
constructor(public http: Http) { }
getCompeletedTasks(){
this.http.get("http://localhost:4000/api/compeleted").subscribe(response =>{
this.compeletedTasks = response.json()
return response.json()})}
}
and this is my component:
import { TasksService } from '../../services/tasks.service';
export class DoneTaskItemsComponent implements OnInit {
constructor(private tasksService:TasksService){}
ngOnInit() {
console.log(this.tasksService.getCompeletedTasks())}
}
I have just deleted things like @component and other things for more readable of codes
So any solution for that? I need to use the compeletedTasks on the template but for now, when I log them on the console, I get undefined
As @Challappan says you need to use httpClient instead of http for making api requests.
Try to change code like below.
getCompeletedTasks(){
return this.http.get("http://localhost:4000/api/compeleted");
}
In component like below.
compeletedTasks: Task[]
ngOnInit() {
this.tasksService.getCompeletedTasks().subscribe(response => {
this.completedTasks = response;
});
}
This link might help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.