【问题标题】:Processing a two-dimensional array in Angular 7. ngFor在 Angular 7 中处理二维数组。ngFor
【发布时间】:2019-06-25 20:38:54
【问题描述】:

如何使用 ngFor 处理二维数组? I receive here such array

因此,我需要获取数组中的数据按顺序显示的块。也就是说,在屏幕上表示的数组的情况下,将有 10 个块。 示例:

<div>
  <span>Yandex</span>
  <span>Yandex.N.V....</span>
  <span>https://en.wikipedia.org/wiki/Yandex</span>
</div>
<div>
  <span>Yandex Browser</span>
  <span>IPA:...</span>
  <span>https://en.wikipedia.org/wiki/Yandex_Browser</span>
</div>

等等

我就是这样做的。

<h3>Get Articles</h3>
<div>
  <div *ngIf="articles">
    <div *ngFor="let article of articles">
      <span>{{ article[1] }}</span>
      <span>{{ article[2] }}</span>
      <span>{{ article[3] }}</span>
    </div>
  </div>
</div>

我知道这是错误的,但我找不到我的愚蠢错误。 输出是错误或strange conclusion

search.component.ts

import { Component, OnInit } from '@angular/core';
import { Article, ArticlesService } from '../../services/articles.service';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css'],
  providers: [ArticlesService]
})
export class SearchComponent implements OnInit {

  constructor(private articlesServices: ArticlesService) { }

  searchQuery: string;
  limit: number;

  error: any;
  articles: { };

  // noinspection JSMethodCanBeStatic
  getUrl(searchQuery: string) {
    return 'https://en.wikipedia.org/w/api.php?action=opensearch&search='
      + searchQuery + '&limit=10&namespace=0&format=json&origin=*';
  }

  showArticles() {
    this.articlesServices.getArticles(this.getUrl(this.searchQuery))
      .subscribe(
        (data: Article) => this.articles = Object.values({
          title: data[0],
          collection: data[1],
          description: data[2],
          links: data[3]
        }),
        error => this.error = error
      );
    console.log(this.articles);
  }


  ngOnInit() {
  }

}

article.component.ts

import { Component, OnInit, Input } from '@angular/core';
import {Article, ArticleInfo, ArticlesService} from '../../services/articles.service';

@Component({
  selector: 'app-articles',
  templateUrl: './articles.component.html',
  styleUrls: ['./articles.component.css'],
})
export class ArticlesComponent implements OnInit {

  @Input() articles: Article;
  @Input() searchQuery: string;

  constructor(private articlesServices: ArticlesService) { }

  information: ArticleInfo;

  getUrl(searchQuery: string) {
    return 'https://ru.wikipedia.org/w/api.php?action=query&list=search&srsearch=' +
      searchQuery + '&utf8=&format=json&origin=*';
  }

  showArticlesInformation() {
    this.articlesServices.getArticlesInfo(this.getUrl(this.searchQuery))
      .subscribe(
        (data: ArticleInfo) => this.information = {
          query: data.query.search
        }
      );
    console.log(this.information);
  }

  ngOnInit() {
  }
}

article.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

export interface Article {
  title: string;
  collection: string[];
  description: string[];
  links: string[];
}

export interface ArticleInfo {
  query: {
    search
  };
}

@Injectable({
  providedIn: 'root'
})
export class ArticlesService {

  constructor(private http: HttpClient) { }

  getArticles(url) {
    return this.http.get(url)
      .pipe(
        retry(3),
        catchError(this.handleError)
      );
  }

  getArticlesInfo(url) {
    return this.http.get<ArticleInfo>(url);
  }

  // noinspection JSMethodCanBeStatic
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError(
      'Something bad happened; please try again later.');
  }
}

Come 2D array

Then it should turn out like this

【问题讨论】:

  • articles 你的二维数组吗?
  • 是的。 articles: [string, string[], string[], string[]
  • 试过嵌套循环吗?
  • 是的。如果你使用这个,就会出现错误。 &lt;div *ngFor="let article of articles"&gt;&lt;div *ngFor=let collection of article[1]&gt;{{ collection }}&lt;/div&gt;&lt;/div&gt;
  • 其中存在语法错误。我在下面给出了答案。

标签: javascript html arrays angular ngfor


【解决方案1】:

尝试将结果存储到 Observable 并使用 async 管道存储到 html 文件中。

<div *ngFor="let article of articles | async">

在你的 search.component.ts

articles : Observable<Article>;
...
this.articles = this.articlesServices.getArticles(this.getUrl(this.searchQuery)).catch(error => this.error = error );

【讨论】:

  • 也许我误解了你。你能更详细地解释一下吗?我还是个新手
  • @Ilya Nizovcev 我已经通过代码进行了更改。请通过
【解决方案2】:

试试这个,

<div>
    {{articles[0]}}
</div>
<div *ngFor="let article of articles[1]; let i=index">
    <span>
        {{article}}
    </span>
    <span *ngFor="let info1 of articles[2]; let j=index" [hidden]="i!=j">
        {{info1}}
    </span>
    <span *ngFor="let info2 of articles[3]; let k=index" [hidden]="i!=k">
        {{info2}}
    </span>
</div>

【讨论】:

  • 谢谢,但错误仍然存​​在 "找不到不同的支持对象 'Yandex' 类型为 'string'。NgFor 仅支持绑定到 Iterables,例如数组"
  • 我认为你的问题很明显,在你的例子中你提到第一个索引是一个字符串。而在这段代码中,第一个索引应该是数组。
  • 引用:[string, string[], string[], string[] 如您所见,第一个索引是字符串,这就是它失败的原因。
  • @IlyaNizovcev 我已经更新了我的答案。看看它是否符合您的要求。
  • 乐于助人:D
猜你喜欢
  • 1970-01-01
  • 2014-07-13
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
相关资源
最近更新 更多