无法将可观察到的分配给打字稿界面

时间:2019-07-16 06:53:27

标签: json angular typescript web-applications get

我从Web-API服务器获得有效的JSON响应,并希望将其保存到Typescript接口实例中。可以获取String,但解析为Car Object时返回未定义的值。

Json字符串

{"id":1,"brand":"Ferrari","hp":700,"available":true, "wheels":"Pirelli", "construction":2019}

car.service.ts文件

import { Injectable } from '@angular/core';
import { Car } from './car.model';
import { Observable, of } from 'rxjs';
import { HttpBackend } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class CarService {

  private carUrl:string=("/api/cars");

  constructor(private httpclient: HttpClient) { }

  getCar():Observable<Car>{

    return this.httpclient.get<Car>(this.carUrl+"/"+localStorage.getItem('selectedID'));
   }
}

car-form.component.ts文件

import { Component, OnInit, Input } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Car } from '../shared/car.model';
import { CarService } from '../shared/car.service';

@Component({
  selector: 'app-car-form',
  templateUrl: './car-form.component.html',
  styleUrls: ['./car-form.component.scss']
})


export class CarFormComponent implements OnInit {
  selectedCarId: number;
  curr_car: Car;
  model: Car = {};

  constructor(private httpclient: HttpClient, private carService: CarService) {

  }

  ngOnInit() {

      this.selectedCarId=Number(localStorage.getItem('selectedID'))
      this.carService.getCar()
      .subscribe(data => this.curr_car=data);
      console.log(this.curr_car)
    }
  }

car.model.ts

export interface Car {
    id?: number;
    brand?: string;
    hp?: number;
    available?: boolean;

}



也许是由于接口没有构造函数引起的!!

0 个答案:

没有答案