一类的访问方法我有一个Angular2应用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看起来类似的问题,但它并没有帮助
从我所看到的,这通常是类型转换的问题。请看看[这个问题](http://stackoverflow.com/questions/32167593/how-to-do-runtime-type-casting-in-typescript)。 –
@AdnanA。 :是的!这是一个演员问题,你的链接真的很有帮助。随意将您的评论更改为答案,我会接受它。 – luc