一類的訪問方法我有一個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