在我的Angular2应用中,我正在尝试使用模块https://www.npmjs.com/package/angular2-phoenix-channels导入Phoenix频道。我遇到一个问题,即尝试访问导入脚本的某些属性会返回“未定义的”#39;错误。
首先,这一切都发生在person.service.ts
。该模块没有打字稿定义文件,因此导入如下:
import * as angular2PhoenixChannels from 'angular2-phoenix-channels';
var PhoenixChannels = angular2PhoenixChannels;
如果我在以下上下文中运行console.log
(日志位于getPerson()的底部):
@Injectable()
export class PersonService {
private apiUrl = 'http://localhost:4000/api/';
private phoenixChannels = PhoenixChannels;
constructor(private http: Http) {
console.log('Service ready...');
}
getPeople(): Promise<Person[]> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http
.get(this.apiUrl + 'people', options)
.toPromise()
.then(response => response.json().data as Person[])
}
getPerson(id: number): Promise<Person> {
console.log(this.phoenixChannels.default.prototype.channel)
return this.getPeople()
.then(people => people.find(person => person.id === id));
}
}
此日志:
function channel(topic) {
return new PhoenixChannel(this.socket, topic);
}
对我来说很好看。但是,如果我尝试将参数传递给channel()
函数,如下所示:
console.log(this.phoenixChannels.default.prototype.channel("testing"))
这会返回错误
Uncaught (in promise): Error: Error in :0:0 caused by: Cannot read property 'channel' of undefined
为什么这个对象突然变得不确定?