在Angular中填充模型

时间:2018-11-12 20:30:05

标签: angular typescript service interface model

我正在从服务中获取对象。

updateComment(id, newcomment) {
const comment: Comment = newcomment;
return this.http.get<any>('http://localhost:3000/cabins/' + id).pipe(
  map(cabin => {


    return {
      id: cabin.id,
      name: cabin.name,
      image: cabin.image,
      description: cabin.description,
      priceweek: cabin.priceweek,
      pricemonth: cabin.pricemonth,
      featured: cabin.featured,
      comments: cabin.comments


    };


  }),
  flatMap((updatedCabin) => {
    updatedCabin.comments.push(comment);
    return this.http.put( + '/' + id, updatedCabin);
  })
);

但是我正在尝试从服务中创建新内容:

export class CompanyFormComponent implements OnInit {


@Input() public companyId: string;
  company: Company;
  companyForm: FormGroup;

  constructor(
    private companyService: CompanyService,
    private fb: FormBuilder
  ) { }

当我console.log数据时,它将显示我想要获取的确切对象。 但是当我在console.log公司工作时,它是this.companyService.getSingle(this.companyId).subscribe( data => { console.log(data); this.company = data; } );

该怎么办?

1 个答案:

答案 0 :(得分:1)

从注释中可以看出,您正在尝试在订阅功能之外进行console.log,该功能在服务获得其响应(异步调用)之前就​​已执行。请尝试以下操作,您应该会看到公司对象的价值:

this.companyService.getSingle(this.companyId).subscribe(
        data => {
          console.log(data);
          this.company = data;
          console.log(this.company)
        }
);