Angular - 如何访问在其他类中定义和保存的JSON响应?

时间:2017-10-07 20:00:49

标签: angular typescript angular-material2

我有一个使用服务login.service.ts进行http Call的组件。 http调用正从DB中检索数据。

我还根据以下example使用MatTableModule作为视图。但我想从响应中动态检索和显示我自己的数据,而不是像示例中那样从硬编码的dataSource中检索和显示。

users.component.ts

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { Http, Headers, RequestOptions, Request, RequestMethod } from '@angular/http';
import { LoginService, UserService} from '../../_service';
import { CustomMaterialModule } from '../../custom-material/custom-material.module';
import { DataSource } from '@angular/cdk/collections';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';

@Component({
    selector: 'app-users',
    templateUrl: './users.component.html',
    styleUrls: ['./users.component.css']
})

export class UsersComponent implements OnInit {

    constructor(private loginService:LoginService, public http: Http) {}

    displayedColumns = ['ID', 'email', 'name'];
    dataSource = new ExampleDataSource();

    errorMessage:any;
    userData: {};

    ngOnInit() { this.retrieveUsers(); }

    retrieveUsers() {
        this.loginService.getUsersList()
        .subscribe(
            (res) => {
                console.log('Get ID: ' + JSON.stringify(res.message[0]._id) );
                this.userData = res.message;
            },(err) => {
                this.errorMessage = err;
            }
        )
    }
}


let test:Object = {
    "error": false,
    "message": [
        {
          "_id": "59415f148911240fc812d393",
          "email": "jane.doe@foo.de",
          "fullName": "Jane Doe",
          "__v": 0,
          "created": "2017-06-14T16:06:44.457Z"
        },
        {
          "_id": "5943b80be8b8b605686a67fb",
          "email": "john.doe@foo.de",
          "fullName": "John Doe",
          "__v": 0,
          "created": "2017-06-16T10:50:51.180Z"
        },
        {
          "_id": "5952476be50d780ab2aa1f88",
          "email": "donovan@foo.de",
          "fullName": "Steve donovan",
          "__v": 0,
          "created": "2017-06-27T11:54:19.879Z"
        },
        {
          "_id": "595247f8e50d780ab2aa1f89",
          "email": "donald@foo.de",
          "fullName": "Donald Duck",
          "__v": 0,
          "created": "2017-06-27T11:56:40.666Z"
        }
    ]
}

export interface Element {
    _id: number;
    email: string;
    fullName: string;
}

const data: Element[] = [
    { _id: test['message'][0]._id, email: test['message'][0].email, fullName: test['message'][0].fullName},
    { _id: test['message'][1]._id, email: test['message'][1].email, fullName: test['message'][1].fullName},
    { _id: test['message'][2]._id, email: test['message'][2].email, fullName: test['message'][2].fullName}
];

export class ExampleDataSource extends DataSource<any> {
    /** Connect function called by the table to retrieve one stream containing the data to render. */
    connect(): Observable<Element[]> {
        return Observable.of(data);
    }

    disconnect() {}
}

问题是我无法访问类组件中的变量userDataUsersComponent,以便将其从类型data传递给ExampleDataSource Element(界面)。

我尝试创建UsersComponent类的实例,并在其余代码中使用它,但它不起作用。

代码中的硬编码JSON对象仅用于测试建议,如果命令检查它是否有效。使用硬编码的JSON,所有数据都将传递给view / html users.component.html并且看起来很干净。

users.component.html

  <div class="example-container mat-elevation-z8">
    <mat-table #table [dataSource]="dataSource">

        <!-- Position Column -->
        <ng-container matColumnDef="ID">
            <mat-header-cell *matHeaderCellDef> ID </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element._id}} </mat-cell>
        </ng-container>

        <!-- Name Column -->
        <ng-container matColumnDef="email">
            <mat-header-cell *matHeaderCellDef> Email </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.email}} </mat-cell>
        </ng-container>

        <!-- Weight Column -->
        <ng-container matColumnDef="name">
            <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.fullName}} </mat-cell>
        </ng-container>

        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>
</div>

以下是我尝试动态传递数据的尝试之一:

const data: Element[] = [
    { _id: this.userData[0]._id, email: this.userData[0].email, fullName: this.userData[0].fullName},
    { _id: this.userData[1]._id, email: this.userData[1].email, fullName: this.userData[1].fullName},
    { _id: this.userData[2]._id, email: this.userData[2].email, fullName: this.userData[2].fullName},
];

如何解决此问题以传递保存在类this.userData中的变量UsersComponent中的响应中的JSON?

1 个答案:

答案 0 :(得分:0)

修正:

<强> users.component.ts

export class UsersComponent implements OnInit {
    displayedColumns = ['ID', 'Email', 'Name'];
    exampleDatabase: RetrieveUsrData | null;
    dataSource: UsrDataSource | null;
    constructor(http: Http) {
      this.exampleDatabase = new RetrieveUsrData(http);
      this.dataSource = new UsrDataSource(this.exampleDatabase);
    }
    ngOnInit(){}
}

export interface UsersData {
  ID: number;
  Email: string;
  Name: string;
}
export class RetrieveUsrData {
    private issuesUrl = 'http://localhost:4000/users';
    getRepoIssues(): Observable<UsersData[]> {
        return this.http.get(this.issuesUrl)
                        .map(this.extractData)
    }
    extractData(result: Response): UsersData[] {
        return result.json().message.map(issue => {
            return {
                ID: issue._id,
                Email: issue.email,
                Name: issue.fullName,
            }
        });
    }
    constructor(private http: Http) {}
}
export class UsrDataSource extends DataSource<UsersData> {
  constructor(private _exampleDatabase: RetrieveUsrData) {
    super();
  }
  connect(): Observable<UsersData[]> {
    return this._exampleDatabase.getRepoIssues();
  }
  disconnect() {}
}