繁体   English   中英

在 Angular 中的模板中显示数据的问题

[英]Problem in displaying data in template in Angular

从 Django 服务器获取数据后,我想在 Angular 中显示它,我使用了:

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

并且没有任何错误,我在模板中看不到数据,上面的代码想要在 JSON 中显示id的值。

服务:

@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({
  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');

 }

}

为什么我看不到模板中的数据,我该怎么做才能在模板中显示?

在您的 TS 文件中,您将this.todo分配给this.api.getApi()的结果,但是该函数的结果是订阅,而不是来自订阅的数据。

您可以将其重写为:

服务.ts:

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

在您的 component.ts 中:

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

这样,您的服务负责与后端交互,您的视图负责将来自服务的数据分配给组件中的正确属性。

希望这可以帮助。

PS。 您不在函数中使用arg参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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