我正在尝试为地图添加一些值。例如,我有以下内容,
我的地址簿课程
export class AddressBook {
constructor(
public social: Map<string, string> = new Map<string, string>(),
) {
}
}
这是服务器返回的内容,
{
social: {
twitter: "twitterId",
facebook: "facebookId",
linkedIn: "linkedinId",
pinterest: "pinterestId"
}
}
这是我添加到社交地图的方法
this.addressBook.social.set('Google+','GooglePlusId');
但是我收到以下错误
caused by: this.addressBook.social.set is not a function
以下是我从服务器检索数据的方法
return this.http.get(this.addressBookURL+address_book_id)
.map(res => <AddressBook> res.json())
.catch(this.handleError);
this.addressBookService.getAddressBookFromId(address_book_id)
.subscribe((res) => {
this.addressBook = res;
},
error => {
console.log(<any>error);
});
不确定如何解决这个问题。如果有人能指出我正确的方向,将非常感激。感谢
答案 0 :(得分:2)
尝试安装@types/core-js
模块,它包含所有es6功能的打字稿定义(Map,Set ...):
npm install @types/core-js --save
you may need to uninstall @types/es6-promise
答案 1 :(得分:1)
我猜你没有将正确的参数传递给AddressBook构造函数。 其实我猜你这样做了:
$ gcc -o a.so -shared -Wall -Wextra -fPIC a.c
$ gcc -o b -Wall -Wextra b.c -L. -l:a.so -Wl,-rpath='$ORIGIN' -ldl
$ ./b
calling foo from main
in foo wrapper
called wrapped foo
calling bar from main
in bar wrapper
called real bar calling
in foo wrapper
called wrapped foo
虽然您应该传递let addressBook= new AdresseBook({
twitter: "twitterId",
facebook: "facebookId",
linkedIn: "linkedinId",
pinterest: "pinterestId"
} as any);
对象...
Map
编辑,我是对的(我总是对的),你不能指望普通对象是地图:
let map = new Map();
let obj = {
twitter: "twitterId",
facebook: "facebookId",
linkedIn: "linkedinId",
pinterest: "pinterestId"
};
Object.keys(obj).forEach(key => {
map.set(key, obj[key]);
});
let addressBook = new AdresseBook(map);
这应该有效:
return this.http.get(this.addressBookURL+address_book_id)
.map(res => <AddressBook> res.json()) //here you are just telling the compiler
// that resp.json() is an AdresseBook, but
// it's not right, it's a plain Object
.catch(this.handleError);