将可观察对象从Web服务转换为数组 - Angular

时间:2017-09-14 11:11:44

标签: arrays angular mapping observable http-get

此项目尝试从Web服务(xml格式)获取数据并将其映射到具有名称,ID,描述等的项目对象。我使用了一个服务来获取和映射数据。

正如您在运行我的应用程序时所看到的,我可以展开Project数组,并且数组中充满了对象。我尝试在HTML文件中显示这个数组,但由于它不是一个对象数组,所以它不允许我。

enter image description here 运行时我在控制台中遇到的错误:

ProjectViewerComponent.html:5错误错误:无法找到不同的支持对象' [object Object]'类型'对象'。 NgFor仅支持绑定到Iterables,例如Arrays。

在这种情况下,如何将我的observables列表(??)转换为数组?我的代码如下:

编辑:现在在我在project.viewer.component的fetchProjects方法中更新我的代码(见下文)后运行它时得到这个

enter image description here

project.model.ts:

export class Project {
    project_id: string;
    name: string;
    description: string;

    constructor(obj: any) {
        this.project_id = obj.project_id;
        this.name = obj.name;
        this.description = obj.description;
    }
}

project.service.ts:

export abstract class ProjectService {
    //methods
    abstract fetchProjects(): Observable<Project[]>;
}

project.service.http.ts:

@Injectable()
export class ProjectServiceHttp extends ProjectService {

    //variables
    baseUrl = "http://dev-teamcity:8090/guestAuth/app/rest/projects";

    //constructor
   constructor(private http: Http) {
        super();
    }

    //methods
    fetchProjects(): Observable<any>{
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});
        return this.http.get(this.baseUrl, options)
          .map((response: Response) => 
          {
            return response.json();
          })
          .catch(this.handleError);
        }


        private handleError(error: any) {
            // In a real world app, we might use a remote logging infrastructure
            // We'd also dig deeper into the error to get a better message
            let errMsg = (error.message) ? error.message :
                error.status ? `${error.status} - ${error.statusText}` : 'Server error';
            console.log(errMsg); // log to console instead
            return Observable.throw(errMsg);
        }

}

project.viewer.component.ts:

@Component({
    selector: 'project-viewer',
    templateUrl: './project-viewer.html',  
    styleUrls: ['./project-viewer.css']
})

export class ProjectViewerComponent  {
    name = 'ProjectViewerComponent';
    projects: Project[];
    errorMessage = "";
    stateValid = true;

    constructor(private service: ProjectService) {
        this.fetchProjects();
    }

    private fetchProjects() {
        this.service
            .fetchProjects()
            .subscribe(response =>{
              this.projects = response['project'];
              console.log(response);
            },
            errors=>{
               console.log(errors);
            });
    }

    private raiseError(text: string): void {
        this.stateValid = false;
        this.errorMessage = text;
    }
}

项目viewer.html:

<h3>Projects </h3>

<div >
    <ul class= "grid grid-pad">
        <a *ngFor="let project of projects" class="col-1-4">
            <li class ="module project" >
                <h4 tabindex ="0">{{project.project_id}}</h4>
            </li>
        </a>
    </ul>
</div>

1 个答案:

答案 0 :(得分:0)

试试这样:

<强> project.service.ts

import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ProjectService {
    baseUrl = "http://dev-teamcity:8090/guestAuth/app/rest/projects";
    constructor(private http: Http) { }

    fetchProjects(): Observable<any> {
        const options = new RequestOptions({ headers: new Headers({ 'Content-Type': 'application/json' }) });
        return this.http.get(this.baseUrl, options).map((res: Response) => {
            const jsonResponse = res.json();
            return jsonResponse;
        });
    }
}

<强> project.viewer.component.ts

export class ProjectViewerComponent  {

    private projects: any;
    constructor(private service: ProjectService) { }

    this.service.fetchProjects().subscribe(data => {
        this.projects = data;
    })
}

在html文件中

<div>{{projects | json}}</div>