简体   繁体   中英

Problem in displaying data in template in Angular

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?

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM