typescript Angular 2:从类创建对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41147695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:05:07  来源:igfitidea点击:

Angular 2: Create objects from a class

classangulartypescript

提问by CanKer DiAlike

Hello I'm wondering if it's possible to create a class where you implement an interface and from there you send the data get from .get service to create a new object. Something like this

您好,我想知道是否可以创建一个类,您可以在其中实现一个接口,然后从那里发送从 .get 服务获取的数据以创建一个新对象。像这样的东西

import { Component, OnInit } from '@angular/core';
import { User} from '../interfaces/user';
import {UserService} from '../services/user.service';
import { UserClass } from  '../classes/user-class'

@Component({
  selector: 'up-pros',
  templateUrl: './pros.component.html',
  providers: [UserService]
})
export class ProsComponent implements OnInit {
  public users :User[];
  public term: string;
  constructor(private _httpService: UserService) { }

  ngOnInit() {
    console.log(UserClass)
    this.term= 'INSTRUCTOR';
    this._httpService.searchUsers(this.term)
        .subscribe(
          data => {this.users = new UserClass(data), console.log(data)},
          error => alert(error + ' Error Get')
        );
  }
}

where my UserClass code is something like next one

我的 UserClass 代码类似于下一个

import { User } from '../interfaces/user';
import { Address } from "../interfaces/address";

export class UserClass implements User {

public  id:           number
public  name:         string
public  password:     string
public  lastNameA:    string
public  lastNameB:    string
public  photo:        string
public  telephone:    string
public  email:        string
public  userType:     string
public  active:       string
public  score:        number
public  createdAt:    string
public  updatedAt:    string
public  Address:      Address

constructor ( id:           number,
              password:     string,
              name:         string,
              lastNameA:    string,
              lastNameB:    string,
              photo:        string,
              telephone:    string,
              email:        string,
              userType:     string,
              active:       string,
              score:        number,
              createdAt:    string,
              updatedAt:    string,
              Address:      Address)  {
                this.name       = name
                this.password   = password
                this.lastNameA  = lastNameA
                this.lastNameB  = lastNameB
                this.photo      = photo
                this.telephone  = telephone
                this.email      = email
                this.userType   = userType
                this.active     = active
                this.score      = score
                this.createdAt  = createdAt
                this.updatedAt  = updatedAt
                this.Address    = Address
              }

}

and by the last, the interface:

最后,界面:

import { Address } from "./address"

export interface User {
  name:       string;
  password:   string;
  lastNameA:  string;
  lastNameB:  string;
  photo:      string;
  telephone:  string;
  email:      string;
  userType:   string;
  active:     string;
  score:      number;
  createdAt:  string;
  updatedAt:  string;
  Address:    Address;
}

Is this possible? because if I try to do this Im getting the next error at pros-component.ts:

这可能吗?因为如果我尝试这样做,我会在 pros-component.ts 中得到下一个错误:

Supplied parameters do not match any signature of call target.
[default] Checking finished with 1 errors

My service:

我的服务:

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { User } from '../interfaces/user';


@Injectable()
export class UserService {
  url= 'http://localhostapi/users';

  constructor(private _http: Http){}


  getUsers(){
    return this._http.get(this.url)
      .map(res => res.json());
  }

  searchUsers(term : string ){
    return this._http.get('http://localhostapi/listas?user='+term)
      .map(res => res.json());

  }
  searchUser(term : string ){
    return this._http.get('http://localhostapi/users/'+term)
      .map(res => res.json());

  }

  postUsers(user: User){

    var headers = new Headers ();
    headers.append('Content-Type','application/json');
    return this._http.post(this.url, user, {headers: headers})
    .map(res => res.json());
  }

  updateUsers(user: User, term: string){

    var headers = new Headers ();
    headers.append('Content-Type','application/json');
    return this._http.put(this.url+"/"+term, user, {headers: headers})
    .map(res => res.json());
  }
}

采纳答案by TheKojuEffect

If the structure of datamatches the list of UserClass, you can simply do

如果的结构data匹配的列表UserClass,你可以简单地做

this._httpService.searchUsers(this.term)
        .subscribe(
          data => {
                      this.users = data as User[];
                      console.log(data)
                  },
          error => alert(error + ' Error Get')
        );