将 XML 从 Web 服务转换为 JSON 并映射到对象 - Angular

Converting XML From Web Service to JSON & Mapping to an object - Angular

编辑:已解决

正在使用 angular 创建项目。 我有一个试图显示对象列表的服务。它使用 http.get 并尝试将响应映射到 json 然后映射到项目的对象(具有项目 ID、名称等属性)问题是数据来自的 Web 服务(在dev-teamcity) 是 XML 格式。

Web 服务如下所示:

当我 运行 我的应用程序时,根本没有返回任何数据。 如何将此 XML 数据映射到我的 Project 对象? 我是 angular 和 JS/TS 的新手,如果能提供任何帮助,我将不胜感激。提前致谢。 我的代码:

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 = "...";

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

    GetProjectStatus(project_id: string): string {
        throw new Error("Method not implemented.");
    }
    GetProjects(project_id: string): Project[] {
        throw new Error("Method not implemented.");
    }


}

project.viewer.component.html:

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

你可以这样做

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 fetchProjects() {
        this.service
            .fetchProjects()
            .subscribe(response =>{
              this.projects = response;
            },
            errors=>{
               console.log(errors);
            }
    });

this.project = response 仅在响应时有效,您 api/backend 发送的是 this.project 的精确副本,您可能必须使用 reponse.data 或 response.result 取决于您的 api returns 的数据格式。您可以console.log(response) 并查看响应格式。

编辑:如果你不想使用选项,你可以调用http.get(this.baseurl),这样调用它。

return this.http.get(this.baseurl)
          .map((response: Response) => {
            return response.json();
          })
          .catch(this.handleError);