我在 type script 上有一堂课:
export class Child {
name:string;
age:number;
}
Run Code Online (Sandbox Code Playgroud)
我想强制类实例只具有类声明所具有的属性。
例如,如果我从 firebase 获取一个对象:
myFirebaseService.getChild(id).then(function(child){
var currentChild = new Child(child);
})
Run Code Online (Sandbox Code Playgroud)
所以当对象是:{name:"ben", color:"db"} 时,我希望结果是:
currentChild = {"name":"ben"}
Run Code Online (Sandbox Code Playgroud)
因为“颜色”不是“孩子”的领域。
我试过这个:
export class Child {
name:string;
age:number;
constructor(tempChild:Child = null) {
if (tempChild){
for (var prop in tempChild) {
this[prop] = tempChild[prop];
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它没有帮助。“currentChild”获取所有字段并将它们附加到类实例。
(当然,我可以使用以下代码:
export class Child {
name:string;
age:number;
constructor(tempChild:Child = null) {
if (tempChild){
this.nam = tempChild.name;
this.age =tempChild.ageÏ;
}
}
}
Run Code Online (Sandbox Code Playgroud)
,但我的真理课有很多字段,我想要短代码)
我是TypeScript的新手,我正在玩各种语言功能.下面是我在许多在线课程中一直在研究的代码示例.
我有问题获得继承和重载以正常工作.在整个代码中,我使用了一辆基本型Auto汽车,以及一辆儿童级卡车.
我试图看看是否有可能将汽车作为卡车投入并访问专门的功能HonkHorn.此外,我正在尝试将卡车投回到Auto并访问WriteDetails的基本功能.
在这两种情况下,似乎对象都保持原始类型.所以typecast4.HonkHorn(); 生成运行时错误:未捕获TypeError:typecast4.HonkHorn不是函数.
尝试将Truck转换为Auto将始终导致调用WriteDetails的专用覆盖.转换代码一直位于示例的底部.
有人可以帮我理解为什么会这样吗?
提前致谢!
// defines the structure of auto options
interface IAutoOptions{
engine: Engine,
color: string,
price: number,
year: number
}
// extends autooptions with truck specific options
interface ITruckOptions extends IAutoOptions{
fourbyfour: boolean,
bedlength: string
}
// defines the structure of engines
interface IEngine {
enginetype: string;
horsepower: number;
hydraulicpump?: string
start(warmuptime: number, callback: () => void): void;
stop(): void;
}
// the engine class must implement the members as specified in the IEngine …Run Code Online (Sandbox Code Playgroud) 我有几个Javascript原型.最初,实例将只填充ID,并为其他数据提供一些通用的占位符信息.然后我使用ID和对象类型(使用jQuery的AJAX函数)向服务器发送消息,服务器返回一个包含所有缺少信息(但没有ID)的JSON对象.返回对象中的变量与现有对象中的变量具有完全相同的名称.
将此转移到现有空对象的最简单方法是什么?我想出了一些替代方案
如果我使用第三个选项,这是正确的方法吗?:
for (var key in json) {
if (object.hasOwnProperty(key)) {
object[key] = json[key];
}
}
Run Code Online (Sandbox Code Playgroud)
假设json是返回的对象并且object是现有对象.
我试图做一个类帖子包含交的属性,如"ID,标题,内容...等.
我想从JSON响应初始化类.我正在使用angular-http来获取打字稿中的JSON
在APP.TS:
class AppComponent {
result: { [key: string]: string; };
map: Map<Object,Object>;
constructor(http: Http) {
http.get('http://localhost/wptest/wp-json/wp/v2/posts').subscribe(res => {
this.result = <any>res.json();
this.map = <any>res.json();
console.log(this.result);
console.log(this.map);
});
}
}Run Code Online (Sandbox Code Playgroud)
注意:我仍然感到困惑的是我的JSON哪个是正确的类型我读过打字稿还没有支持Map,但它在这里工作如result: {[key:string]: string; };
我试着查看stackoverflow,我发现这个问题如何将一个json对象转换为打字稿,答案与打字稿无关.
在另一个问题中我可以创建一个TypeScript类型并在AJAX返回JSON数据时使用它吗?
答案是谈论在打字稿中创建接口.(我不太明白.)
我还发现json2ts的这个站点从JSON生成typescript接口,所以我尝试了我的json,我得到了这个:
declare module namespace {
export interface Guid {
rendered: string;
}
export interface Title {
rendered: string;
}
export interface Content {
rendered: string;
}
export interface Excerpt { …Run Code Online (Sandbox Code Playgroud)我基于Angular2教程创建了一个非常简单的应用程序.
首先,我有一个非常简单的"书"模型:
/**
* book model
*/
export class Book {
public data;
/**
* constructor
* @param id
* @param title
* @param pages
*/
constructor(
public id,
public title:string,
public pages:Array
){
alert('it works'); // just a check
}
}
Run Code Online (Sandbox Code Playgroud)
在我的服务中,我得到了这样一本书:
return this._http.get('getBook/1')
.map(function(res){
return <Book> res.json();
})
Run Code Online (Sandbox Code Playgroud)
我的期望是,这将获得生成的JSON数据并将其"映射"到Book对象.
但是,它只返回一个类型为"Object"的对象.
我可以自己创建一个新的Book对象并在构造函数中传递参数,如下所示:
return new Book(res.id, res.title, res.pages);
Run Code Online (Sandbox Code Playgroud)
这是最好的方法吗?我错过了什么?
我正在使用以下代码集并使用本地存储获取强类型项目。
该集按预期工作并将 JSON 放入本地存储中。
但是,当取出相同的项目时,转换为通用类型似乎不起作用。它不会引发异常,只是返回 JSON 字符串,而不是所需的类型化对象。
export class StorageService {
constructor() { }
setItem<T>(key: string, item: T): void {
localStorage.setItem(key, JSON.stringify(item));
}
getItem<T>(key: string): T {
let data: any = localStorage.getItem(key);
if (!data) return null;
let obj: T;
try {
obj = <T>JSON.parse(data);
} catch (error) {
obj = null;
}
return obj
}
}
Run Code Online (Sandbox Code Playgroud) 在Typescript中,我有一个Contact实现接口的类IContact.我想在类中添加一个属性或函数,Contact它返回另外两个字段(firstname和lastname)的组合.IContact界面的定义如下:
export interface IContact {
firstname: string;
lastname: string;
}
Run Code Online (Sandbox Code Playgroud)
这个Contact类看起来像这样:
export class Contact implements IContact {
constructor(
public firstname: string,
public lastname: string
) { }
public fullname(): string {
return this.firstname + " " + this.lastname;
}
}
Run Code Online (Sandbox Code Playgroud)
在我看来,我想输出结果,Contact.fullname()但我收到的错误fullname不是函数.我可以访问该类的所有其他属性.
====更新===
我会添加一些额外的代码来澄清一些东西.当我fullname在我的视图中输出属性时,我已尝试contact.fullname()但也contact.fullname没有结果.在我的组件中,试图弄清楚发生了什么,我试图fullname像这样输出到控制台:console.log("FULLNAME " +contact.fullname());,但是在控制台中给我以下消息:EXCEPTION _this.contact.fullname is not a function
=====更新答案========
正如Sakuto所说,联系人列表是由服务器收到的一些json创建的.通过调用它的构造函数完全创建一个新实例,我能够输出fullname属性.谢谢Sakuto!
我有一个英雄按钮列表,其中创建了自定义动画button.component.ts.一开始,他们不活跃.当我按下其中一个时,所选的一个应该变为活动状态.为此,我在hero.ts被调用state的函数中创建了一个字段,并在toggleState()其中更改了状态.但是当我按下按钮时,我收到错误:
EXCEPTION:http:// localhost:3000/app/button.component.js中的错误类ButtonComponent - 内联模板:4:10由:self.context引起.$ implicit.toggleState不是函数
我的猜测是我不能像我在这里那样创建自定义方法.但我是Angular2中的新手,所以我无法说出来.我做错了什么?我玩得很好"哪里是Wally?" 用我的代码仍然找不到任何东西.
button.component.ts:
import { Component, Input, OnInit, trigger, state, style, transition, animate
} from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
moduleId: module.id,
selector: 'button-collection',
template: `
<button *ngFor="let hero of heroes"
[@heroState]="hero.state"
(click)="hero.toggleState()">
{{hero.name}}
</button>
`,
styleUrls: ['heroes.component.css'],
animations: [
trigger('heroState', [
state('inactive', style({
backgroundColor: '#e1e1e1',
transform: 'scale(1)'
})),
state('active', style({
backgroundColor: '#dd1600',
transform: 'scale(1.1)' …Run Code Online (Sandbox Code Playgroud) 我有JSON数组如下:
var json = [{
id: 1,
login: "Mieszko",
name: "Misztal",
surname: "Adminek",
phone: "0413414",
role: 2
},
{
id: 2,
login: "Rafal",
name: "Robak",
surname: "Kierowczek",
phone: "5145145",
role: 1
}
];
Run Code Online (Sandbox Code Playgroud)
我还创建了User类,如下所示:
export class User extends BaseModel {
id: number;
login: string;
name: string;
surname: string;
phone: string;
roles: Roles;
admin: boolean;
driver: boolean;
isDriver(): boolean {
return this.roles === 1;
}
//other methods
}
Run Code Online (Sandbox Code Playgroud)
我的计划是将命令JSON数组转换为User数组.在JSON内部,我获得了整数角色.我班上有管理员和驱动程序布尔字段.这在复选框的ngModel中是必需的.
现在问题出在这一行之后
var users: Array<User> = JSON.parse(JSON.stringify(json));
Run Code Online (Sandbox Code Playgroud)
我无法从User类调用方法,例如users[0].isDriver()因为编译器无法识别isDriver()方法.
有谁知道如何解决这个问题?
有谁知道如何将JSON响应解析为这样的结构?
[
{
"iD": 2,
"OrderList": [
{
"bidPrice": 0,
"iD": 0,
"name": "Name",
"price": 10,
"resteurant": "Restaurant"
},
{
"bidPrice": 0,
"iD": 0,
"name": "Something",
"price": 20,
"resteurant": "La Place"
}
],
"owner": "Tom"
}
]
Run Code Online (Sandbox Code Playgroud)
我使用json2ts来创建这两个结构:
import {OrderList} from "./OrderList.ts";
import {Injectable} from "@angular/core";
@Injectable()
export interface OrderBasket {
iD: number;
OrderList: OrderList[];
owner: string;
}
Run Code Online (Sandbox Code Playgroud)
和
import {Injectable} from "@angular/core";
@Injectable()
export interface OrderList {
bidPrice: number;
iD: number;
name: string;
price: number;
resteurant: string;
}
Run Code Online (Sandbox Code Playgroud)
我打电话给服务器并订阅,但我不能得到这个结构.有人可以帮忙吗?
让这个JSON字符串:
[
{
"id": 1,
"text": "Jon Doe"
},
{
"id": 1,
"text": "Pablo Escobar"
}
]
Run Code Online (Sandbox Code Playgroud)
让我们上课:
export class MyObject{
id: number;
text: string;
}
Run Code Online (Sandbox Code Playgroud)
如何将此JSON字符串转换为列表MyObject?
如果我做:
console.log(<MyObject[]>JSON.parse(json_string));
Run Code Online (Sandbox Code Playgroud)
它返回一个列表Object而不是列表MyObject
我有一个像这样的Json数组:
[{"name":"ip","children":{"label":"ip","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"test","children":{"label":"test","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"join","children":{"label":"join","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"myform","children":{"label":"myform","value":"","type":"text","validation":"{ required: true}"}}]
Run Code Online (Sandbox Code Playgroud)
我应该将一个对象传递给这样的组件
export const person = {
ip: {
label: 'ip',
value: '',
type: 'text',
validation: { required: true }
},
test: {
label: 'test',
value: '',
type: 'text',
validation: { required: true }
},
join: {
label: 'join',
value: '',
type: 'text',
validation: { required: true }
},
myform: {
label: 'myform',
value: '',
type: 'text',
validation: { required: true }
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
typescript ×11
angular ×5
json ×3
ajax ×1
casting ×1
constructor ×1
generics ×1
inheritance ×1
interface ×1
javascript ×1
jquery ×1
object ×1
rxjs ×1