私はAngular 4アプリを持っています。RxJSで購読した後にオブジェクトのタイプが正しくない
私はAPIのURLでFirebaseデータベースからデータをフェッチするサービスがあります。
import { Product } from './../models/product';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AppSettings } from '../app-settings';
@Injectable()
export class ProductsService {
products = [];
constructor(private http: HttpClient) { }
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(AppSettings.DB_API_ENDPOINT + '/products.json',);
}
}
そして、そのデータを表示するコンポーネント:
import { Product } from './../../models/product';
import { Component, OnInit, Input } from '@angular/core';
import { ProductsService } from '../../services/products.service';
import { CategoriesService } from '../../services/categories.service';
@Component({
selector: 'products-list',
templateUrl: './products-list.component.html',
styleUrls: ['./products-list.component.scss']
})
export class ProductsListComponent implements OnInit {
products: Product[];
numberOfProducts: number;
page: number;
constructor(private productsService: ProductsService, private categoriesService: CategoriesService) {
this.page = 1;
this.numberOfProducts = 0;
this.products = [];
}
ngOnInit() {
this.productsService.getProducts().subscribe(products => {
console.log(products[0].getId());
this.products.push(products[0] as Product);
this.numberOfProducts = this.products.reduce((prev, el) => {
return prev + el.qtyAvailable;
}, 0);
});
}
qtyChange(qty: number) {
this.numberOfProducts -= qty;
}
}
とモデルProduct
:
export class Product {
$key: string;
qty: number;
isSoldOut: boolean;
constructor(
private id: number,
private name: string,
private description: string,
public qtyAvailable: number,
private price: number,
private image: string,
public category: string
) {
this.isSoldOut = false;
this.qty = 0;
}
isAvailable() {
return !this.isSoldOut;
}
getImageUrl() {
return '/assets/images/products/' + this.image;
}
public getId(): number {
return this.id;
}
getPrice() {
return this.price;
}
getDescription() {
return this.description;
}
getName(): string {
return this.name;
}
}
を
そのコンポーネントの観点から、私はproduct.isAvailable()
メソッドを使用しますモデルProduct
。コンソールERROR TypeError: _co.product.isAvailable is not a function
にエラーメッセージが表示されます。コンパイル中にproducts[0].id
と入力するとエラーメッセージが表示されますが、そのid
はプライベートなProduct
です。このエラー・メッセージのために、プロダクトのリストは表示され、ページ番号が付けられますが、データはありません。
'で、より多くのクリーナーです'**はキャストやコンバージョンを行いません**、コンパイラのヒントに過ぎません。そのクラスのインスタンスが必要な場合は、自分でインスタンスを作成する必要があります。 JSONデータは、プロパティが設定された単なるオブジェクトになります。 – jonrsharpe
はい、わかっています。私はサービス 'subscribe'メソッドでProductオブジェクトを作成しようとしましたが、フィールドがprivateであるというコンパイラエラーが発生しました(つまり、TypeScriptがProductタイプのように扱うことを示しています)、つまり' getId() 'getId()'は関数ではないのでJSコンソールでエラーが発生します(JSは 'Product'型のように扱います)。そして、私は今すぐ立ち往生しています。 – michalk93
あなたが知っていて、試したことがありますか?*その試みの[mcve] **を表示してみませんか?* – jonrsharpe