У меня есть компонент center-prices.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { PriceRule } from '../models/price-rule';
import { PriceRulesService } from '../services/price-rules.service'
@Component({
selector: 'app-center-prices',
templateUrl: './center-prices.component.html',
providers: [PriceRulesService],
styles: [`
nb-card {
width: 300px;
}
nb-select {
width: 125px;
}`],
})
export class CenterPricesComponent implements OnInit {
centerprices: PriceRule[];
pricerule: PriceRule;
errorMessage: string;
constructor(
private priceruleService: PriceRulesService,
private route: ActivatedRoute
) {}
ngOnInit() {
this.getPriceRule();
}
getPriceRule() {
//const id = this.route.snapshot.paramMap.get('id');
this.priceruleService.getPriceRule('1')
.subscribe(
pricerule => this.pricerule = pricerule
);
}
}
Услуга:
import { Injectable } from '@angular/core';
import { PriceRule } from '../models/price-rule';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class PriceRulesService {
private url: string = 'http://localhost:5555/price_rules';
constructor(private http: HttpClient) {
this.http = http;
}
getPriceRules(): Observable<PriceRule[]> {
return this.http.get<PriceRule[]>(this.url);
}
getPriceRule(id: string): Observable<PriceRule> {
return this.http.get<PriceRule>(`${this.url}/${id}`)
.map(response => PriceRule.fromJson(response));
}
addPriceRule(p: PriceRule) {
return this.http.post(this.url, p);
}
delPriceRule(id: string) {
return this.http.delete<PriceRule>(`${this.url}/${id}`);
}
}
Я использую поддельный json-сервер благодаря пакету npm json-server
вот так: sudo json-server -p 5555 price_rules.json
price_rules.json:
{
"price_rules": [
{
"id": "1",
"activity": "Tennis",
"duration": 45,
"is_indoor": false,
"surface": "code",
"hour_start": "08:00",
"hour_end": "17:00",
"price": 1500,
"currency": "EUR",
"weekdays": [
1,
2,
3,
4,
5,
6,
7
]
},
{
"id": "2",
"activity": "Badminton",
"duration": 90,
"is_indoor": true,
"surface": "code",
"hour_start": "10:00",
"hour_end": "18:00",
"price": 1600,
"currency": "EUR",
"weekdays": [
1,
2,
3,
4,
5
]
}
]
}
Сервер работает, моя проблема, когда я console.log
pricerule
в компоненте, это результат в консоли: {}
Когда я console.log
response
в функции getPriceRule
службы, все детали, которые мне нужны, отображаются в консоли.
Вот класс PriceRule
export class PriceRule {
public static fromJson(json: Object): PriceRule {
return new PriceRule(
json['id'],
json['activity'],
json['duration'],
json['is_indoor'],
json['surface'],
json['hour_start'],
json['hour_end'],
json['price'],
json['currency'],
json['weekdays']
);
}
constructor(
id: string,
activity: string,
duration: number,
is_indoor: boolean,
surface: string,
hour_start: string,
hour_end: string,
price: number,
currency: string,
weekdays: number[]
){ }
}
Я также заметил, что GET возвращает код 304 Not modified
в консоли в разделе networks