尝试创建动态ng2 search.service

时间:2017-07-20 23:20:26

标签: javascript angular typescript design-patterns

我正在尝试创建动态ng2 search.service。 REST服务是在我的组织中搜索数据的基础协议。这是我最初创建的用户搜索用户的服务:

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

@Injectable()
export class UserService {

    private headers = new Headers({ 'Content-Type': 'application/json' });
    private usersUrl = 'http://localhost:4000/users';
    private userUrl = 'http://localhost:4000/users/@id';

    constructor(private http: Http) { }

    getUser(id: number): Promise<User> {
        return this.http.get('http://localhost:4000/users/1')
            //return this.http.get(this.userUrl.replace('@id', id)) 
            .toPromise()
            //.then(this.extractData)
            .then(response => response.json())
            .catch(this.handleError);
    }

    getUsers(): Promise<User[]> {
        return this.http.get(this.usersUrl)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

    private extractData(response: Response) {
        return response.json();
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}

这是我第一次尝试通用search.service:

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

@Injectable()
export class SearchService
{
    private _headers = new Headers({ 'Content-Type': 'application/json' });
    private _entityName = '';
    private _allEntitiesUrl = 'http://localhost:4000/@entityNames';
    private _entityByIdUrl = 'http://localhost:4000/@entityNames/@id';

    constructor(private http: Http, entityName: string)
    {
        this._allEntitiesUrl = entityName + 's';
        this._entityByIdUrl = entityName + 's';
    }

    getEntity(id: number): Promise<User>
    {
        var url = this._entityByIdUrl.replace('@id', id.toString());
        return this.http.get(url)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

    getEntities(): Promise<User[]>
    {
        return this.http.get(this._allEntitiesUrl)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

    private extractData(response: Response)
    {
        return response.json();
    }

    private handleError(error: any): Promise<any>
    {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}

search.service现在只是部分完成。以下是我知道需要更新的一些内容:

  1. import语句需要是通用的,或者以某种方式容纳可能从search.service返回的不同类型的实体。例如,search.service可能会返回帐户,产品等:

    从&#39; ../ entities / user&#39;;

  2. 导入{User}
  3. 我需要弄清楚如何为getEntity / getEntities实现动态返回类型。我已经做了一些工作来实现从C#返回泛型类型的方法,但不确定如何使用ng2 / typescript

  4. 我确定我不是第一个考虑过这样做的人,所以希望其他能更流利使用ng2 /打字稿的人可以解释我如何实现这个目标?

1 个答案:

答案 0 :(得分:0)

  

import语句需要是通用的,或者以某种方式容纳可能从search.service返回的不同类型的实体。例如,search.service可能会返回帐户,产品等:

在TypeScript中,您可以创建interface,然后让不同的项实现该接口。然后,您的搜索服务可以返回您的界面类型。 e.g。

class User implements Entity

然后服务

getEntities(): Promise<Entity[]>
{
    return this.http.get(this._allEntitiesUrl)
        .toPromise()
        .then(response => response.json())
        .catch(this.handleError);
}
  

我需要弄清楚如何为getEntity / getEntities实现动态返回类型。我已经做了一些工作来实现从C#返回泛型类型的方法,但不确定如何使用ng2 / typescript

如您所述,另一个选项是使用generics例如

getEntities<T>(): Promise<T[]>
{
    return this.http.get(this._allEntitiesUrl)
        .toPromise()
        .then(response => response.json())
        .catch(this.handleError);
}

将被称为

getEntities<User>()