我无法将可观察对象转换为自定义对象的选定字段(BookDetails:可以说Class除了Title以外具有所有变量)。尽管进行了强制转换,但我仍然能够在与我在其中调用服务的组件相对应的html文件中访问Title。
我有一个返回以下JSON的API:
[{"id":1,
"Title":"The Intelligence Trap",
"Description":"Why smart people do stupid things and how to make wiser decisions",
"Author":"David Robson",
"FinishDate":"2019-11-08",
"EShop":"https://www.amazon.in"}]
我需要捕获除了Title 以外的所有内容,因此我将myservice.ts中http.get函数的Observable输出转换为BookDetails类。我在打算使用该服务的地方创建了一个新组件。我订阅了该服务,但仍可以在相应组件的html文件中访问Title。这是预期的行为吗?
下面是PullData.service.ts文件中的代码
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { BookDetails } from "../Interfaces/book-details";
@Injectable({
providedIn: "root"
})
export class PullDataService {
constructor(private http: HttpClient) {}
public getDataFromService(): Observable<BookDetails[]> {
return this.http.get<BookDetails[]>(
"http://127.0.0.1:8000/Generic/newroute/"
);
}
public getDummyDataFromService(): Observable<BookDetails[]> {
return this.http.get<BookDetails[]>("/app/data/dummy.json");
}
}
这是BookDetails.ts中的代码
import { Url } from "url";
export class BookDetails {
id: number;
Author: string;
FinishDate: Date;
Description: string;
EShop: Url;
}
我也尝试过将此作为接口..无济于事。 node_package中提供了“ URL”。 请注意,这里没有标题!
**import { Url } from "url";
export class BookDetails {
id: number;
Author: string;
FinishDate: Date;
Description: string;
EShop: Url;
}**
这是组件的打字稿文件
import { Component, OnInit } from "@angular/core";
import { PullDataService } from "../PullData/pull-data.service";
import { BookDetails } from "../Interfaces/book-details";
@Component({
selector: "app-roles",
templateUrl: "./roles.component.html",
styleUrls: ["./roles.component.scss"]
})
export class RolesComponent implements OnInit {
public books: BookDetails[];
constructor(private pds: PullDataService) {}
ngOnInit() {
this.pds.getDataFromService().subscribe(data => (this.books = data));
}
}
这是组件的html文件
<ul>
<li *ngFor="let book of books">
Title: {{ book.Title }}
</li>
</ul>
我正在使用Angular8。页面上没有错误,并且数据库中所有记录的输出的标题行都很整洁。有人可以帮我知道我在做什么错吗?我累了! :(
答案 0 :(得分:0)
您没有创建BookDetails
类的对象。您正在接收对象并使用它(您仅尝试进行类型转换。它不会更改对象结构。)。如果要排除接收到的对象的Title
属性,则必须从对象中删除Title
属性,或者需要创建对象类BookDetails
使用构造函数。
课程
export class BookDetails {
id: number;
Author: string;
FinishDate: Date;
Description: string;
EShop: Url;
constructor(serverObject) {
Object.assign(this, serverObject)
}
}
组件
import { Component, OnInit } from "@angular/core";
import { PullDataService } from "../PullData/pull-data.service";
import { BookDetails } from "../Interfaces/book-details";
@Component({
selector: "app-roles",
templateUrl: "./roles.component.html",
styleUrls: ["./roles.component.scss"]
})
export class RolesComponent implements OnInit {
public books: BookDetails[];
constructor(private pds: PullDataService) {}
ngOnInit() {
this.pds.getDataFromService().subscribe(data => {
this.books = data.map(dataObj => new BookDetails(dataObj))
});
}
}