这是我的代码。我只是尝试对本地服务器执行GET并获取响应(这是一个JSON对象),然后将其发送到其他角度组件。 由于某种原因,它说错误TypeError:this.sendData不是一个函数
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做一些简单的事情,但是到目前为止在角度上做起来显然很痛苦。我正在学习有角度的教程,这些教程似乎涵盖了不同的用例。任何帮助将不胜感激,可能只是格式问题。谢谢你。
答案 0 :(得分:2)
像这样使用箭头功能
this.http.get<myData>
(this.base_path + '/get/goldProducts',
this.httpOptions).subscribe
(res => {
this.sendData(res);
});
答案 1 :(得分:2)
查看此
this.http.get<yourData>
(this.base_path + '/get/goldProducts',
this.httpOptions).subscribe
(res => {
//handle your data
this.sendData(res);
});
答案 2 :(得分:1)
您可以通过这种方式使用箭头功能。
getGoldProducts(){
this.httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
}
return this.http.get<myData>(this.base_path + '/get/goldProducts', this.httpOptions)
.subscribe((res: any) => {
console.log(res);
this.sendData(res);
});
}
答案 3 :(得分:0)
您应该使用 Fat arrow (脂肪箭头)功能(Lambda表达式)。粗箭头 => 分隔功能参数和功能主体。 => 的右侧可以包含一个或多个代码语句。此外,它放弃了使用“ 功能 < / strong>”关键字。在TypeScript中,在:之后但在=(赋值)之前的所有内容都是类型信息。
getGoldProducts(){
this.httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
}
//drop the use of function keyword while subcribing and use fat arrow instead.
return this.http.get<myData>(this.base_path + '/get/goldProducts',this.httpOptions).subscribe(res => {
console.log(res);
this.sendData(res);
});
}