【问题标题】:Converting an observable object from a web service to an array - Angular将可观察对象从 Web 服务转换为数组 - Angular
【发布时间】:2018-02-23 08:19:49
【问题描述】:

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

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

运行时我在控制台中遇到的错误:

ProjectViewerComponent.html:5 ERROR 错误:找不到“object”类型的不同支持对象“[object Object]”。 NgFor 只支持绑定到数组等 Iterables。

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

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

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;
    }
}

project-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>

【问题讨论】:

  • 您的响应对象包含计数、href 和项目数组。您应该分配给项目项目数组:this.projects = response.project.
  • this.projects = response.json(); 应该可以解决问题并在 *ngFor 末尾添加| async
  • @lingthe 如果我尝试在组件类的 fetchProjects 方法中执行 this.projects = response.project,它会给我“属性 'project' 在类型 'Project[]' 上不存在”
  • 您没有 project_id 属性:{{project.project_id}} 应该是 {{project.id}}
  • 您应该在 fetchProjects 函数中执行此操作 - 如果您想要第一个 9 而不是使用 response['project'].splice(0, 9) 但如果您想要特定的 9 那么您应该首先制作一个数组这九个 id 并创建了将通过项目的函数,并且在 this.projects 中仅推送具有 sutable id 的对象。对每个项目使用,并将项目中的每个 id 与数组中的 id 进行比较。

标签: arrays angular mapping observable http-get


【解决方案1】:

试试这样:

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>

【讨论】:

  • 它无法访问服务,因为它不在构造函数内? [ts] 意外的令牌。需要构造函数、方法、访问器或属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多