【问题标题】:Angular2 : access method of a class in templateAngular2:模板中类的访问方法
【发布时间】:2017-03-30 12:10:17
【问题描述】:

我在 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 看起来类似的问题,但没有帮助

【问题讨论】:

  • 据我所知,这通常是类型转换的问题。请看this question
  • @AdnanA。 : 是的!这是一个选角问题,你的链接真的很有帮助。随意将您的评论更改为答案,我会接受。

标签: javascript angular


【解决方案1】:

如果数据是异步获取的,你需要提防null

{{ contact?.getStatus() }}

【讨论】:

  • 我不认为这是一种类型。我想调用contact 对象的getStatus。 contacts 是列表
  • 我明白了。我在搜索 contact 时错过了这一点。我更新了我的答案。
【解决方案2】:

正如@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();
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多