[英]Return JSONArray from a Service Api Rest in Angular
I am fairly new to Angular and Api Rest.我对 Angular 和 Api Rest 相当陌生。 I want call a URL from the service and respond with a JSONArray.
我想从服务中调用 URL 并使用 JSONArray 进行响应。 For example: https://jsonplaceholder.typicode.com/posts
例如: https://jsonplaceholder.typicode.com/posts
I'm calling a service from App.component and return a JSONArray but it show only from console.我从 App.component 调用服务并返回 JSONArray 但它仅从控制台显示。
My App.component:我的 App.component:
import { Component, OnInit } from '@angular/core';
import { DataApiService } from 'src/app/services/data-api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private rest: DataApiService) { }
ngOnInit() {
this.getListProducts();
}
getListProducts(){
this.rest.getAllProducts().subscribe(data => {
console.log(data);
});
}
}
My Service:我的服务:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataApiService {
constructor(private http: HttpClient) { }
getAllProducts(){
const localUrl = 'assets/data/smartphone.json';
return this.http.get(localUrl);
}
}
Here how you access data在这里您如何访问数据
Declare variable声明变量
myData:any;
then catch that data然后捕获该数据
catchAndPrint(data)
{
this.myData:any=data;
console.log("Return data :",this.myData);
}
in your function在你的 function
ngOnInit() {
this.getListProducts();
}
getListProducts(){
this.rest.getAllProducts().subscribe(data => {
this.catchAndPrint(data);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.