我为我正在开发的一个应用程序在Angular2中创建了一些与可观察功能相关的函数。但从那以后我就没用过角。因此,为了在Angular8中发挥作用,我必须相应地修改与可观察性相关的工作函数,而我无法消除一些错误消息。
来自服务器的API从数据库返回一个对象数组:
router.get('/getEntries, (req, res, next) => {
db.get().collection('data').find().toArray((err, data) => { res.json(data); });
});问题可能在entry.service.ts文件中:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {Entry} from '../Classes/entry';
@Injectable()
export class EntryService {
constructor(private http: HttpClient) { }
getEntries(): Observable<Entry[]> {
return this.http.get('http://192.168.1.3:3000/api/getEntries').pipe(map(res => res.json() as Entry[]));
}
} //end of Serviceapp.component.ts如下:
import {Component, OnInit} from '@angular/core';
import {Entry} from '../Classes/entry';
import {EntryService} from '../Services/entry.service';
@Component({
selector : 'app-root',
templateUrl : './app.component.html',
styleUrls : ['./app.component.css']
})
export class AppComponent implements OnInit {
entries: Entry[];
constructor(private entryService: EntryService) { }
ngOnInit(): void {
this.entryService.getEntries().subscribe(data => {this.entries=data;}, err => {console.log(err);});
}
} //end of Component在entry.service.ts中使用的旧Angular2文件如下:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Entry } from '../Classes/entry';
import 'rxjs/add/operator/map';
@Injectable()
export class EntryService {
constructor(private http: Http) { }
getEntries(): Observable<Entry[]> {
return this.http.get('http://192.168.1.3:3000/api/getEntries').map(res => res.json() as Entry[]);
}
} //end of Service现在,在角8中,.json()函数不再存在。我如何调整我的代码角8,以便工作??
一般来说,我处理http请求的方法是一个很好的做法,还是可以以更好的方式实现?我不知道角度的深度,所以这就是为什么我要问。
提前谢谢您的时间!
发布于 2019-11-07 10:37:59
如果您使用的是角4.3.x或更高版本,请使用来自HttpClientModule的HttpClientModule类:
从“@ HttpClientModule /公用/http”导入{};
imports: [
BrowserModule,
HttpClientModule
],
...
class MyService() {
constructor(http: HttpClient) {...}这是一个升级版的http,来自@angular/http模块,有以下改进:
您可以阅读它是如何工作的这里。
还请注意,旧http是使用Http类令牌注入的,而不是新的HttpClient。
@NgModule({
imports: [
BrowserModule,
HttpModule
],
...
class MyService() {
constructor(http: Http) {...}发布于 2019-11-07 10:33:45
HttpClient.get()自动应用res.json()并返回Observable>。您不再需要自己调用此函数。
不需要使用这种方法:
.map((res: Response) => res.json());https://stackoverflow.com/questions/58746683
复制相似问题