我为正在开发的应用程序在Angular2中创建了一些与Observables相关的功能。但是从那时起,我就再也没有使用过Angular了。因此,我的与Observable相关的工作功能必须进行相应的修改才能在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 Service
app.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
Angular2中的旧工作 entry.service.ts 文件如下:
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
现在,在Angular 8中, .json()函数不再存在。 我如何在Angular 8中调整代码才能正常工作?
通常来说,我处理http请求的方法是一种好的做法还是可以以更好的方式实现?我不了解Angular,所以这就是我要问的原因。
提前感谢您的时间!
答案 0 :(得分:0)
HttpClient.get()
自动应用res.json()
并返回Observable>。您不再需要自己调用此函数。
请参见Difference between HTTP and HTTPClient in angular 4?
不需要使用此方法:
.map((res: Response) => res.json());
答案 1 :(得分:0)
如果您使用的是Angular 4.3.x及更高版本,请使用HttpClient
中的HttpClientModule
类:
从'@ angular / common / http'导入{HttpClientModule};
imports: [
BrowserModule,
HttpClientModule
],
...
class MyService() {
constructor(http: HttpClient) {...}
这是@ angular / http模块的http升级版本,具有以下改进:
您可以了解其工作原理here。
还要注意,旧的http是使用Http
类令牌而不是新的HttpClient
@NgModule({
imports: [
BrowserModule,
HttpModule
],
...
class MyService() {
constructor(http: Http) {...}