javascript - Angular 2 - 未捕获( promise ): RangeError: Maximum call stack size exceeded

原文 标签 javascript json typescript angular2-services

我问你关于我的 Typescript 代码中的一个问题。
我正在使用 json 格式的 Google Places API。我的问题是我无法通过 ID 获取信息,导致错误是: RangeError: Maximum call stack size exceeded

我看到我是否有一个无限循环,但我没有。

///////////////////////restaurant.services.ts/////////////////

import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { Restaurant } from "../class/restaurant.class";
import "rxjs/add/operator/map";
import "rxjs/add/operator/do"; 
import "rxjs/add/observable/of";
import "rxjs/add/operator/catch";

@Injectable()

export class RestaurantServices {

    private data: any;
    private observable: Observable<any>;
    private url: string = 'app/api/restaurant.json'

    constructor(private  http:  Http){}

    getRestaurantFromAPIWithCache() {

        if (this.data) {
            return Observable.of(this.data);
        } else if (this.observable) {
            return this.observable;
        } else {
            this.observable = this.http
                .get(this.url)
                .map(res => res.json())
                .map(response => {
                    this.observable = null;
                    this.data = response;
                    return this.data;
                })
                .catch(error => {
                    let errorMsg = 'une erreur ${error.status} est survenu en tentant de joindre ${error.url}';
                    return Observable.throw(errorMsg);
                });

            return this.observable;
        }
    }

    getRestaurantById(id:any) {
        if (!this.data) {
            return undefined;
        }
        const result = this.data.filter((resto: any) => resto.id === id);
        console.log("Dans restoServices: "+result);
        if (result.length > 0) {
            return result[0]; // recupère le premier élément du tableau
        }
    }

}

restaurant.list.ts
import { Component, OnInit } from "@angular/core";
import { Restaurant } from "./class/restaurant.class";

import { RestaurantServices } from "./services/restaurant.services";

@Component({
  moduleId: module.id,
  templateUrl: "restaurant-list.component.html",
  styleUrls: ['./css/restaurant.css']
})

export class RestaurantListComponent implements OnInit {

  restos: Restaurant[];
  errorMsg: string = "";

  constructor(private _restoServices: RestaurantServices) { }

  ngOnInit() {
    //Called after the constructor, initializing input properties, and the first call to ngOnChanges.
    //Add 'implements OnInit' to the class.
    this._restoServices.getRestaurantFromAPIWithCache()
      .subscribe(res => {
        this.restos = res.results;
      });
  }
}

餐厅列表.html
<div *ngFor="let resto of restos">
<div class="col-sm-6 col-md-4">
        <div class="thumbnail">
          <div *ngFor="let images of resto.photos" >
            <img src="https://maps.googleapis.com/maps/api/place/photo?maxwidth=640&maxheight=640&photoreference={{images.photo_reference}}&key=AIzaSyA2VI_ZemIgFgbXo7sHtUms7E7NhURqhTw" alt="img">
          </div>
              <div class="caption">
                <h3>{{resto.name}}</h3>
                  <p id="cityArea">{{resto.vicinity}}</p>
                  <a [routerLink]="['/restaurant', resto.id]">
                    <button type="button" class="btn btn-info center-block" data-toggle="modal" data-target="#myModal">Details <span class="glyphicon glyphicon-info-sign"></span></button>
                  </a>
              </div>
         </div>
      </div>

餐厅.detail.ts
///////////////////////restaurant.details.ts/////////////////

import { Component, OnInit, Input } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";

import { Restaurant } from "./class/restaurant.class";
import { RestaurantServices } from "./services/restaurant.services";

@Component({
    moduleId:module.id,
    selector:"resto-details",
    templateUrl:"restaurant-details.component.html",
    styleUrls:['./css/restaurant.css']
})

export class RestaurantDetailsComponent implements OnInit{

    @Input() rt:Restaurant;
    resto:Restaurant;
    title:string ="";

    constructor(private route:ActivatedRoute, private router:Router, private _restoServices:RestaurantServices){}

        ngOnInit() {
            //Called after the constructor, initializing input properties, and the first call to ngOnChanges.
            //Add 'implements OnInit' to the class.

            let id= +this.route.snapshot.params['id'];
            this.resto= this._restoServices.getRestaurantById(id);
            console.log("ID detailPage "+ id);
        }

        goBack(){
            this.router.navigate(['/restaurant']);
        }


}

Restaurant.details.html
<resto-details [rt]="resto"></resto-details>

<br>
       <!-- Modal -->
  <div *ngIf="resto">
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h2 class="modal-title" id="myModalLabel">{{ rt.name }}</h2>
          </div>
          <div class="modal-body">
              <!-- Description du restaurant  -->
              <div>{{ rt.name }}</div>
              <div>{{ rt.vicinity | uppercase}}</div><br>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal" (click)='goBack()'>Close</button>
          </div>
        </div>
      </div>
    </div>
  </div>              
<div *ngIf="!resto">Pas de Restaurant correspondant trouvée</div>

如果你有什么想法。
谢谢你提前。

最佳答案

完成了...我刚刚更换

const result = this.data.filter((resto: any) => resto.id === id);



经过

this.data.results.filter((resto: any) => resto.id === id);

关于javascript - Angular 2 - 未捕获( promise ): RangeError: Maximum call stack size exceeded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46953872/

相关文章:

javascript - 在 Typescript 的同一类中从另一个方法调用方法

javascript - $(“html,body”)。animate({scrollTop:0},'slow');在我的页面中不起作用

javascript - 旋转.obj文件OBJMTLLoader three.js

javascript - 根据语言更改警报消息?

JSON Unicode转义序列-是否小写?

node.js - 使用NestJS在OPTIONS上找不到404

typescript - 如何从记录类型创建区分联合类型?

javascript - 当scrollTop为0时如何检测用户是否正在滚动div内容?

javascript - Leaflet:MarkerCluster 可用的多边形中心对象

java - Java JSON POST无法正确格式化