0

After fetching data from Django server I want to display it in Angular, I used :

 <p>
  {{todo.id}}
</p>

and without any errors, I do not see the data in my template, the above code wants to display the value of id in a JSON.

service:

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {

  }
  private URL="http://127.0.0.1:8000/api/product/"
  getApi(arg:any){
    console.log(arg);
    return this.http.get (this.URL)
    .subscribe(data=> {
      console.log('we got',data)
    })
    console.log(arg);
    
  }
  
}

component:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']

})
export class AppComponent {
   
  title = 'angpr';
  todo:any;

  constructor(public api: ApiService) {

    

  }

 ngOnInit(): void{
  this.todo=this.api.getApi('hey');

 }

}

Why can't I see the data in template and what should I do to display it in the template?

1
  • 2
    Don’t subscribe in your service, just return the observable and subscribe in the component. Commented Jun 20, 2022 at 17:30

1 Answer 1

1

In your TS file you assign this.todo to the result of this.api.getApi(), however the result of that function is a subscription and not data that comes from subscribing.

You can rewrite this to:

service.ts:

getApi(arg:any):Observable<any>{
    console.log(arg);
    return this.http.get (this.URL)    
}

And in your component.ts:

this.api.getApi('hey').subscribe(
   result => this.todo = result
)

In this way your service is responsible for interacting with the backend and your view is responsible for assigning the data from the service to the correct attributes in your component.

Hope this helps.

PS. You don't use the arg parameter in the function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.