[英]Problem in displaying data in template in Angular
After fetching data from Django server I want to display it in Angular, I used :从 Django 服务器获取数据后,我想在 Angular 中显示它,我使用了:
<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.并且没有任何错误,我在模板中看不到数据,上面的代码想要在 JSON 中显示id
的值。
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.在您的 TS 文件中,您将this.todo分配给this.api.getApi()的结果,但是该函数的结果是订阅,而不是来自订阅的数据。
You can rewrite this to:您可以将其重写为:
service.ts:服务.ts:
getApi(arg:any):Observable<any>{
console.log(arg);
return this.http.get (this.URL)
}
And in your component.ts:在您的 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. PS。 You don't use the arg parameter in the function.您不在函数中使用arg参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.