Angular2:模板中类的访问方法

时间:2016-11-16 10:25:58

标签: javascript angular

我在Angular2应用程序中有以下类

export class Contact {

  constructor(
    public has_reply: boolean,
    public archived: boolean
  ) {  }

  getStatus() : string {
    if (this.archived) {
      return "Archived";
    }

    if (this.has_reply) {
      return "Answered";
    }

    return "Waiting";
  }
}

由服务

返回
@Injectable()
export class ContactsService {

  private contactsData : BehaviorSubject<Array<Contact>> = null;

  constructor(private http: Http) {
    this.contactsData = new BehaviorSubject<Array<Contact>>([]);
  }

  /**
   * get the list of contacts
   */
  populateContacts() : Array<Contact> {
    return this.http.get('/api/contacts/').map(
      (res: Response) => {return res.json()}
    ).subscribe(
      jsonData => {
        this.contactsData.next(<Array<Contact>> jsonData);
      }
    );
  }

  onContactsChanged() : Observable<Array<Contact>>{
    return this.contactsData.asObservable();
  }

}

用于组件

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  private contacts: Array<Contact>  = [];

  constructor(
    private contactsApi : ContactsService
  ) { }

  ngOnInit() {
    this.contactsApi.onContactsChanged().subscribe(
      (contacts: Array<Contact>) => {this.contacts = contacts;}
    );
    this.contactsApi.populateContacts();
  }

}

并显示在模板中

<table class="table table-striped table-bordered">
  <tr *ngFor="let contact of contacts">
    <td>
     {{ contact.getStatus() }}
    </td>
  </tr>

我收到以下错误

EXCEPTION: Error in ./HomeComponent class HomeComponent - inline
template:11:8 caused by: self.context.$implicit.getStatus is not a function

我的做法有什么问题? Angular2是否允许调用这样的类方法?

注意:Calling method from a Angular 2 class inside template看起来类似问题,但没有帮助

2 个答案:

答案 0 :(得分:1)

根据@AdnanA的建议,问题是一个投射问题。见How to do runtime type casting in TypeScript?

我通过强制转换数组的每个对象来修复:请参阅https://stackoverflow.com/a/32186367/117092

// Thank you! https://stackoverflow.com/a/32186367/117092
function cast<T>(obj, cl): T {
  obj.__proto__ = cl.prototype;
  return obj;
}

@Injectable()
export class ContactsService {

  private contactsData : BehaviorSubject<Array<Contact>> = null;

  constructor(private http: Http) {
    this.contactsData = new BehaviorSubject<Array<Contact>>([]);
  }

  /**
   * get the list of contacts
   */
  populateContacts() : Array<Contact> {
    return this.http.get('/api/contacts/').map(
      (res: Response) => {return res.json()}
    ).subscribe(
      jsonData => {
        // WRONG! this.contactsData.next(<Array<Contact>> jsonData);
        // FIXED BY
        let contactsArray: Array<Contact> = [];
        for (let i=0, l=jsonData.length; i<l; i++) {
          let contact = cast<Contact>(jsonData[i], Contact);
          contactsArray.push(contact);
        }
        this.contactsData.next(contactsArray);
      }
    );
  }

  onContactsChanged() : Observable<Array<Contact>>{
    return this.contactsData.asObservable();
  }

}

答案 1 :(得分:0)

如果数据是异步获取的,则需要防范null

{{ contact?.getStatus() }}