筛选从Web服务获取的json数组以仅包含某些元素-Angular [英] Filtering a json array obtained from a web service to only contain certain elements - Angular

查看:123
本文介绍了筛选从Web服务获取的json数组以仅包含某些元素-Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个项目,该项目使用来自Web服务的HTTP获取并返回带有ID,名称,描述等的项目数组.

I am creating a project which uses a HTTP get from a web service and returns an array of projects, with ID, name, description etc.

此Web服务中有很多项目,但是我只关心其中的9个,其余的都无关紧要.

There is many projects within this web service but I am only concerned with 9 of them the rest are irrelevant.

我有一个想要的9个项目的集合,这些项目在project.service.http.ts类中声明了唯一的ID,我只想显示这些ID.

I have a desired set of 9 projects with unique ID's declared in the project.service.http.ts class that I want to only be showing.

我试图过滤HTTP get请求,使其仅包含9个特定的ID,这些ID存储在字符串类型的projectIds数组中.

I am trying to filter the HTTP get request to only include the 9 specific Ids, which I store in a projectIds array of type string.

通过记录响应:

With logging the response:

已解决编辑问题: 我从以下位置更改了project.viewer.component中的构造函数:

EDIT SOLVED: I changed the constructor in the project.viewer.component from :

 constructor(private service: ProjectService) {
        this.service.fetchProjects().subscribe(response => {
          this.projects = response.filter(elements => {
            // BaseComponent was my class. Use yours.
            return ProjectViewerComponent.projectIds.includes(elements.id);
          });
        })
      }

至:

 constructor(private service: ProjectService) {
        this.service.fetchProjects().subscribe(response => {
          this.projects = response['project'].filter(elements => {
            // BaseComponent was my class. Use yours.
            return ProjectViewerComponent.projectIds.includes(elements.id);
          });
        })
      }

关键是this.projects = response之后的['project']

The Key was the ['project'] after the this.projects = response

project.service.http.ts:

project.service.http.ts:

@Injectable()
export class ProjectServiceHttp extends ProjectService {

    //variables
    baseUrl = "http://...";

        static projectIds: string[] = ["..."
                                ,"...", "..","..."];

        //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) => 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:

project.viewer.component.ts:

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


export class ProjectViewerComponent  {
    name = 'ProjectViewerComponent';
    projects: Project[] = [];

    static testIds: string[] = ['qqq', 'aaa'];

    static projectIds: string[] = ["...","..."
    ,"..","..","...","..."
    ,"..", "...","..."];

    errorMessage = "";
    stateValid = true;

      constructor(private service: ProjectService) {
        this.service.fetchProjects().subscribe(response => {
          this.projects = response.filter(elements => {
            return ProjectViewerComponent.projectIds.includes(elements.id);
          });
        })
      }

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

project-viewer.html:

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.name}}</h4>
            </li>
        </a>
    </ul>
</div>

推荐答案

服务中的方法fetchProjects()可以在其他组件中重复使用.因此,您可能希望它返回所有项目,因为这是此方法的目的.提取所有项目.

The method fetchProjects() from your service could be re-used in another component. So you might want it to return all the projects, since it's the aim of this method. To fetch all the projects.

第一种方法(推荐):

最好的办法是过滤从HTTP调用返回中获得的数据.

The best thing would be to filter the data you get from the return of your HTTP Call.

这样,您需要过滤从服务中获取的数据,以仅显示该组件中想要的内容.

In that way, you need to filter the data you get from the service to display only what you want in that component.

project.viewer.component.ts:

.subscribe(response =>{
  this.projects = response.project.
    .filter(elements => someCondition);
  console.log(response);
  console.log(this.projects);
},

第二种方法(不推荐):

只有当您确定不再需要所有项目时,才需要使用.map()方法来更改从服务调用获取的数据.当然,您可以执行另一个函数,该函数将调用相同的URL而不过滤该数据,但随后您将必须维护两个方法来进行基本上相同的调用.这就是为什么最好在组件而不是服务中过滤数据.

The only time you will want to use the .map() method to change the data you get from your service call is when you are sure you won't ever need to have all the projects, but only these ones. Of course, you could do another function that would call the same URL and not filter that data, but then you will have to maintain two methods doing basically the same call. That's why it's better to filter your data in your component and not in your service.

尽管如此,您仍需要在服务中更改此部分:

Nonetheless, you would need to change this part in your service :

project.service.http.ts (应称为 project.service.ts btw)

.map((response: Response) => {
  const results = response.json();
  return = results.filter(elements => someCondition);
})


这是您的类对象和我自己的模拟数据的有效解决方案:


EDIT : Here is the working solution with your class object and my own mock data :

project.service.http.ts :最初,请勿使用.filter() .

project.service.http.ts : Initial one, don't use .filter().

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

project.viewer.component.ts:

由于我采用了一些代码来做一个简单的示例(我的项目ID为'qqq''aaa'),因此您需要进行一些调整.

You will need to adapt a bit since I took some of your code to do a fast example (my projects IDs are 'qqq' and 'aaa').

  static projectIds: string[] = ['yourIds', 'YourIds2', ...];

  projects: Project[] = [];

  constructor(private service: ProjectService) {
    this.service.fetchProjects().subscribe(response => {
      this.projects = response.filter(element => BaseComponent.projectIds.includes(element.id)); // BaseComponent was my class. Use yours.
    })
  }

project-viewer.html: 未更改.

在我的示例中,我的服务向我发送了4个项目,我过滤了其中的2个以仅显示2个项目.效果很好,请告诉我在适应代码时是否遇到任何问题.

In my example, my service sends me 4 projects, and I filter 2 of them to only display 2. Works great, tell me if you have any problem adapting to your code.

如您所见,这是我首先提到的第一个方法的应用.出于第二种方法中所述的原因,也不要将此方法也应用于服务.

As you can see, this is the application of the first method I mentionned first. Do not apply this to the service as well for the reasons stated in the second method.

这篇关于筛选从Web服务获取的json数组以仅包含某些元素-Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆