是否可以在Angular2(Typescript)中创建一个Parser类来处理响应?

时间:2017-02-06 06:09:12

标签: parsing angular angular2-services

我知道我可以在Angular 2(Typescript)中创建一个组件和服务,并且可以解析组件中的响应,但我希望我的架构如下所示,响应中的任何更改我将只需要更改解析器:

  

服务:执行API调用和获取响应。有一个获得响应的方法。

     

Parser:获取响应并解析响应并以可用的形式将响应返回给组件。

     

组件:从解析器获取响应并显示要查看的数据。

为了做到这一点,我使用服务中的observable并在解析器中订阅它。然后使用解析器中的observable并在组件中订阅它。

但这样做会导致很多错误。我是否会错过任何步骤,或者是解决问题的正确方法。

添加代码:

组件:::

    import { AuthenticateParser } from './../../parsers/authenticate.parser';
    import { Component, OnInit } from '@angular/core';
    @Component({
     selector: 'my-component',
     moduleId: module.id,
     templateUrl: './app.component.html',
     providers : [AuthenticateParser]
    })
    export class AppComponent implements OnInit {
     // Constructor Function
     constructor(private _authenticationService: AuthenticateParser) {
     }
     ngOnInit(): void {
      this._authenticationService.setAuthenticationToken();
     }
    }

服务:::

import { Observable } from 'rxjs/Observable';
import { IRequest } from './api.interaction.interface';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';

@Injectable()
export class ApiInteractionService {
 // Constructor Function
 constructor(private _http: Http) {
 }
 getApiResponse(p_attr: IRequest): Observable<Response> {
    // Set request url
    let _authenticationUrl: string = p_attr.url;
    // Set request body
    let _body: any = p_attr.body;
    // Set content type to JSON
    let _headers = new Headers(p_attr.header);
    // Set a request option
    let _options = new RequestOptions({ headers: _headers });

    return this._http[p_attr.method](_authenticationUrl, _body, _options)
        .map((response: Response) => response.json()) ///... change response to JSON format
        .do((data:any) => console.log('All : ' + JSON.stringify(data))) //... console response
        .catch((error: any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}}

PARSER :::

import { Injectable, Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { IRequest } from './../services/api.interaction.interface';
import { ApiInteractionService } from './../services/api.interaction.service';

@Injectable()
export class AuthenticateParser {
 private _authenticationToken: string = '';
 // Constructor Function
 constructor(private _authenticationService: ApiInteractionService) {
 }
 // Fetches Authentication Token
 setAuthenticationToken(): void {
    let p_url: string = 'http://10.5.214.82:8443/auth/authenticate';
    let p_body: Object = {
        "userId": "admin",
        "password": "admin"
    };
    let p_header: Object = {
        "Content-Type": "application/json"
    };
    let p_attrs: IRequest = {
        'method': 'post',
        'url': p_url,
        'body': p_body,
        'header': p_header
    };
    this._authenticationService.getApiResponse(p_attrs)
        .subscribe(
        response => this.parseSuccessResponse(response),
        error => this.parseErrorResponse(error)
        );
    }
    // Parses Token response and sets it.
    parseSuccessResponse(p_response: any): void {
      this._authenticationToken = p_response.data;
    }
    // Parses Error response and sets it.
    parseErrorResponse(p_error: any): void {
      this._authenticationToken = p_error.data;
    }
    // returns authentication token
    getAuthenticationToken():string {
     return this._authenticationToken;
    }
}

1 个答案:

答案 0 :(得分:2)

听起来您想将解析器作为服务。如果您提供示例代码,会有所帮助。

在解析器中,您可以订阅http.get响应,然后解析响应,然后将结果发布到主题。然后在您的组件中,您从解析器订阅主题。

您的解析器将类似于:

import { Injectable, OnInit} from '@angular/core';
import { Subject } from 'rxjs/Subject';
import {YourService} from '....''

@Injectable()
export class ParseService implements OnInit {
  public parseSubject: Subject<any> = new Subject <any>();
  constructor(private service: YourService) {}
  ngOnInit(){
   this.service.yourGetFunction()
      .map(res=> res.json())
      .subscribe(
           response => { 
                 parse logic that stores result in parsedObj
                 parseSubject.next(parsedObj);
            },
            error => { this.errorMessage = <any>error});
   }
}

现在在您的组件中,您可以导入ParseService并订阅其parseSubject以获取已解析的输出