【发布时间】:2020-01-01 05:17:53
【问题描述】:
这是我的代码。我只是尝试对本地服务器执行 GET 并获取响应(这是一个 JSON 对象)并将其发送到不同的角度组件。 由于某种原因,它说 ERROR TypeError: this.sendData is not a function
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
interface myData {
data: Object
}
@Injectable({
providedIn: 'root'
})
export class ApiService {
goldProducts: any[] = [];
httpOptions: any;
constructor(private http: HttpClient) {}
base_path = 'http://localhost:80';
shareData = new Subject<any>();
sendData(data: any) {
this.shareData.next(data);
}
getGoldProducts() {
this.httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
}
return this.http.get<myData>(this.base_path + '/get/goldProducts', this.httpOptions).subscribe(function(res) {
console.log(res);
this.sendData(res);
});
}
}
它要去的组件是:
import { Component } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { ApiService } from '../services/api.service';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
goldProducts: any[] = [];
getItemPrices: any[] = [];
constructor(public api: ApiService, public http: HttpClientModule) { }
displayGoldProducts() {
this.api.shareData.subscribe(data => {
console.log(data);
});
this.api.getGoldProducts();
}
}
函数 displayGoldProducts() 只是简单地连接到 html 中的一个按钮。 我将获得正确的响应控制台日志,但仅来自 api.service。 我不知道如何把它连接起来。我只想要一个可观察的,所以当我从服务器推送新价格的新数据时,客户端上的价格将自动更新。在 javascript 中做一些简单的事情,但在 angular 中做这件事显然很痛苦。我正在学习角度,教程似乎涵盖了不同的用例。任何帮助将不胜感激,可能只是格式问题。提前谢谢你。
【问题讨论】:
-
当你调用
sendData时,试试看this的值是多少。它可能是调用函数,而不是类 - 要解决这个问题,请考虑使用箭头函数(res)=>{}。
标签: javascript angular ionic-framework