Angular 从服务Api Rest返回JSONArray
我对Angular和Api Rest相当陌生。我想从服务中调用一个URL并用JSONArray响应。例如: 我从App.component调用一个服务并返回一个JSONArray,但它只从控制台显示 我的应用程序组件:Angular 从服务Api Rest返回JSONArray,angular,Angular,我对Angular和Api Rest相当陌生。我想从服务中调用一个URL并用JSONArray响应。例如: 我从App.component调用一个服务并返回一个JSONArray,但它只从控制台显示 我的应用程序组件: import { Component, OnInit } from '@angular/core'; import { DataApiService } from 'src/app/services/data-api.service'; @Component({ sele
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);
});
}
}
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);
}
}
我的服务:
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);
});
}
}
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);
}
}
这里介绍如何访问数据 声明变量
myData:any;
然后捕捉数据
catchAndPrint(data)
{
this.myData:any=data;
console.log("Return data :",this.myData);
}
在你的职责范围内
ngOnInit() {
this.getListProducts();
}
getListProducts(){
this.rest.getAllProducts().subscribe(data => {
this.catchAndPrint(data);
});
}
您需要更改代码
console.log(数据)
从App.component返回你想要的任何东西,返回一个JSONArray但它只从控制台显示是什么意思?我想从android应用程序调用函数,但我不知道如何返回数据。我使用“邮递员”来测试我的GET请求,但它在主体中返回视图组件的“HTML”。我在您的服务上看不到任何可见内容。但是不管你怎么导入它。尝试使用一些接口添加observable。所以它会自动绑定