Angular 2+和缺少属性

时间:2018-10-25 20:06:42

标签: angular

我的Windows控制台出现错误,但是程序在chrome中正确运行,并且可以执行我的操作。错误:

  

src / app / modules / profile / components / add-comment / add-comment.component.ts(36,37)中的错误:错误TS2345:“配置文件”类型的参数无法分配给“配置文件”类型的参数'。     类型“个人资料”中缺少属性“ fullName”。

听起来很奇怪。我只想设置我的主题资料。出了什么问题?

我的服务:

import { Injectable } from '@angular/core';
import { Profile } from '../models/profile';
import { HttpClient } from '@angular/common/http';
import { Subject, Observable } from 'rxjs';

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

  private _profileUrl: string = "/assets/mocks/profile.json";
  profile$: Subject<Profile> = new Subject<Profile>();

  constructor(private _http: HttpClient) {
    this._http.get(this._profileUrl).subscribe( (resProfile: Profile) => {
      this.profile$.next(resProfile);
    })
  }

  getProfile(): Observable<Profile> {
    return this.profile$.asObservable();
  }

  setProfile(profile: Profile): void {
    this.profile$.next(profile)
  }

}

我的组件

import { Component, OnInit } from '@angular/core';
import { Profile } from 'selenium-webdriver/firefox';
import { ProfileService } from 'src/app/services/profile.service';

import { Comment } from '../../../../models/comment';

@Component({
  selector: 'app-add-comment',
  templateUrl: './add-comment.component.html',
  styleUrls: ['./add-comment.component.scss']
})
export class AddCommentComponent implements OnInit {

  profile: Profile;
  displayComments: boolean = true;

  constructor(private _profileService: ProfileService) { }

  ngOnInit() {
    this._profileService.getProfile().subscribe( (resProfile: any) => {
      this.profile = resProfile;
    })
  }

  onAddCommentEnter(commentText: string): void {
    let profileTmp: Profile = this.profile;

    let comment: Comment = {
      fullName: 'Tomasz Mitura',
      time: 'now',
      text: commentText
    }

    profileTmp.comments.push(comment);
    console.log('profileTmp', profileTmp);
    this._profileService.setProfile(profileTmp);
  }

}

2 个答案:

答案 0 :(得分:1)

编辑::您没有导入正确的Profile类。 替换

import { Profile } from 'selenium-webdriver/firefox';

作者

import { Profile } from '../models/profile';

在您的组件中(编辑从您的组件到Profile类的路径)。


如果您导入了正确的Profile,只需重新启动控制台/ IDE / ng serve

可能是因为它在缓存中保留了Profile的旧原型。

答案 1 :(得分:0)

在第3行的组件中,请注意,您是从

导入Profile类。

import { Profile } from 'selenium-webdriver/firefox';

但是我相信你想要的是

import { Profile } from '../models/profile';

您的服务正在使用同一个人。