Issue
I am learning angular 10. Below is my service where I am fetching data from inbuilt API
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class UsersService {
constructor(private http:HttpClient) { }
getData() {
let url = 'https://jsonplaceholder.typicode.com/todos/';
return this.http.get(url);
}
}
This API returns data as array
of objects
but when I try to assign this data in my app.component.ts
to one array
variable it says this data is object
.
import { Component } from '@angular/core';
import { UsersService } from './users.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'routing-demo';
data=[]
constructor(private user:UsersService) {
this.user.getData().subscribe(data=>{
this.data=data
console.log(data)
})
}
}
I do tried below solutions as well
this.data.push(data);
But getting same error as
"TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Type 'Object' is missing the following properties from type 'never[]': length, pop, push, concat, and 26 more."
Solution
You should set the correct types (stackblitz):
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
interface Data {
userId: number;
id: number;
title: string;
completed: boolean;
}
@Injectable({
providedIn: 'root'
})
export class UsersService {
constructor(private http: HttpClient) {}
getData(): Observable<Data[]> {
let url = "https://jsonplaceholder.typicode.com/todos/";
return this.http.get<Data[]>(url);
}
}
import { Component } from '@angular/core';
import { UsersService } from './users.service';
interface Data {
userId: number;
id: number;
title: string;
completed: boolean;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'routing-demo';
data: Data[] = [];
constructor(private user: UsersService) {
this.user.getData().subscribe(data=>{
this.data = data;
console.log(data);
})
}
}
You data type is:
interface Data {
userId: number;
id: number;
title: string;
completed: boolean;
}
and the response contains an array of it. You should create a file like data.ts
with
export interface Data {
userId: number;
id: number;
title: string;
completed: boolean;
}
and import it in your component and service.
Answered By - Thomas Sablik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.