Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular &引用;错误:未捕获(承诺中):类型错误:无法读取属性';长度';“未定义”的定义;_Angular_Typescript - Fatal编程技术网

Angular &引用;错误:未捕获(承诺中):类型错误:无法读取属性';长度';“未定义”的定义;

Angular &引用;错误:未捕获(承诺中):类型错误:无法读取属性';长度';“未定义”的定义;,angular,typescript,Angular,Typescript,有人能帮我纠正这个错误吗 "Error: Uncaught (in promise): TypeError: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined at SomeComponent.webpackJsonp.805.SomeComponent.getBList (http://localhost:4200/1.chunk.js:23

有人能帮我纠正这个错误吗

"Error: Uncaught (in promise): TypeError: Cannot read property 'length' of undefined

TypeError: Cannot read property 'length' of undefined
    at SomeComponent.webpackJsonp.805.SomeComponent.getBList (http://localhost:4200/1.chunk.js:23613:34)
    at SomeComponent.webpackJsonp.805.SomeComponent.ngOnInit (http://localhost:4200/1.chunk.js:23610:14)
    at checkAndUpdateDirectiveInline (http://localhost:4200/vendor.bundle.js:11957:19)
    at checkAndUpdateNodeInline (http://localhost:4200/vendor.bundle.js:13336:17)
    at checkAndUpdateNode (http://localhost:4200/vendor.bundle.js:13304:16)
    at debugCheckAndUpdateNode (http://localhost:4200/vendor.bundle.js:13933:59)
    at debugCheckDirectivesFn (http://localhost:4200/vendor.bundle.js:13874:13)
    at Object.eval [as updateDirectives] (ng:///SeasonPageModule/SeasonPageComponent_Host.ngfactory.js:16:5)
    at Object.debugUpdateDirectives [as updateDirectives] (http://localhost:4200/vendor.bundle.js:13859:21)
    at checkAndUpdateView (http://localhost:4200/vendor.bundle.js:13271:14)
    at callWithDebugContext (http://localhost:4200/vendor.bundle.js:14259:42)
    at Object.debugCheckAndUpdateView [as checkAndUpdateView] (http://localhost:4200/vendor.bundle.js:13799:12)
    at ViewRef_.detectChanges (http://localhost:4200/vendor.bundle.js:11368:63)
    at RouterOutlet.activateWith (http://localhost:4200/vendor.bundle.js:32580:42)
    at ActivateRoutes.placeComponentIntoOutlet (http://localhost:4200/vendor.bundle.js:31760:16)
    at ZoneAwareError (http://localhost:4200/vendor.bundle.js:95038:33)
    at resolvePromise (http://localhost:4200/vendor.bundle.js:94728:31)
    at resolvePromise (http://localhost:4200/vendor.bundle.js:94713:17)
    at http://localhost:4200/vendor.bundle.js:94762:17
    at ZoneDelegate.invokeTask (http://localhost:4200/vendor.bundle.js:94502:35)
    at Object.onInvokeTask (http://localhost:4200/vendor.bundle.js:5362:37)
    at ZoneDelegate.invokeTask (http://localhost:4200/vendor.bundle.js:94501:40)
    at Zone.runTask (http://localhost:4200/vendor.bundle.js:94378:47)
    at drainMicroTaskQueue (http://localhost:4200/vendor.bundle.js:94660:35)"
我试图从json文件中获取内部数组的值,并将其转换为我创建的变量。 我的json文件的格式如下

JSON filename: file.json
    {
      "A":[
        {
          "id": "123",
          "title": "title of A",
          "type": "asf",
          "B": [
            {
              "id": "1",
              "title": "title1"
            },
            {
              "id": "2",
              "title": "title2"
            }
          ]
      ]
    }
我创建了两个模型来存储这些值

A.model.ts
import {B} from './b.model';

export interface A {

    type?;

    id?;

    title?;

    b?: B[];

}

B.model.ts
export interface B {

    id?;

    title?;

}
返回json的服务具有以下特性

someService.service.ts

import {A} from '../model/a.model';
constructor(private _http: Http, private _authService: AuthService) {}

  get() {
    return this._http.get('app/file.json')
                    .toPromise()
                    .then(res => <A[]> res.json().showList)
                    .then(A => { return A; });
  }
someService.service.ts
从“../model/A.model”导入{A};
构造函数(private http:http,private authService:authService){}
得到(){
返回此文件。_http.get('app/file.json'))
.toPromise()
.then(res=>res.json().showList)
。然后(A=>{返回A;});
}
在component.ts中,我编写了以下代码

<somename>.component.ts

import { Component, OnInit } from '@angular/core';
import { Routes, Router } from '@angular/router';
import {Observable} from 'rxjs';

import {A} from '../../shared/model/a.model';
import {SomeService} from '../../shared/service/someService.service';
import {B} from '../../shared/model/b.model';
import {Location} from '@angular/common';

class AList implements A {
  constructor(public title?, public id?, public type?, public bList?: B[]) {}
}
class BList implements B {
  constructor(public title?, public id?) {}
}

@Component({
  selector: 'ms-season-page',
  styleUrls: [],
  template: require('./season-page.component.html')
})
export class SomeComponent implements OnInit {

  b: B = new BList();

  bArray: B[] = [];

  aArray: A[];

  constructor(private router: Router, private someService: SomeService) {
  }

  ngOnInit() {
    this.someService.get().then(a => this.aArray = a);
    this.bArray = this.getBList(this.aArray);
  }

  getBList(aArray: AList[]): B[] {
    let bList: B[] = [];
    for(let j=0; j<aArray.length; j++) {
        for (let i=0; i<aArray[j].seasonList.length; i++) {
          let b = new BList(aArray[j].B[i].title, aArray[j].B[i].id);
          bList.push(b);
        }
    }
    return bList;
  }
}
.component.ts
从“@angular/core”导入{Component,OnInit};
从'@angular/Router'导入{Routes,Router};
从“rxjs”导入{Observable};
从“../../shared/model/A.model”导入{A};
从“../../shared/service/SomeService.service”导入{SomeService};
从“../../shared/model/B.model”导入{B};
从“@angular/common”导入{Location};
类实现了{
构造函数(public title?,public id?,public type?,public bList?:B[]){}
}
类BList实现了B{
构造函数(公共标题?、公共id?{}
}
@组成部分({
选择器:“ms季节页面”,
样式URL:[],
模板:require(“./seasure page.component.html”)
})
导出类SomeComponent实现OnInit{
b:b=新的BList();
bArray:B[]=[];
aArray:A[];
构造函数(专用路由器:路由器,专用someService:someService){
}
恩戈尼尼特(){
this.someService.get().then(a=>this.aArray=a);
this.bArray=this.getBList(this.aArray);
}
getBList(aArray:AList[]):B[]{
让bList:B[]=[];
for(设j=0;j此
res.json().showList
错误。
json
返回承诺。承诺没有
showList
成员

修理 更多
.

问题在于,
此.someService.get
是异步的,您试图访问它的结果,就像它是同步的一样:

this.someService.get().then(a => this.aArray = a); // This is asynchronous
this.bArray = this.getBList(this.aArray); // This will be called before `this.aArray` is set to anything. Now `this.aArray` will be undefined
修复方法是在异步方法的回调中使用
this.aArray

this.someService.get().then(a => {
  this.aArray = a;
  this.bArray = this.getBList(this.aArray); // Now `this.aArray` will have some value provided `someService.get()` returns something
});

实际上我不能正确地修改。我的服务就像get(){返回这个。_http.get('app/file.json').toPromise()。然后(res=>res.json().A)。然后(A=>{returna;});}当我使用这个时,我可以得到'A'的值(即id、title和A的类型)但是无法获得B的值。我在其他一些场景中使用了相同的方法,效果很好。可能最好写为
this.\u http.get('app/file.json').map(res=>res.json().showList)。toPromise()
。将从
可观察的
承诺的转换放在最后,并利用本地的可观察操作符。嗨,尼尔·伦恩,我已经尝试了你建议的方法,但没有太大差别,错误仍然是一样的。实际上我的问题是
getBList(aArray:AList[]):B[{让bList B[]=[];for(让j=0;jWell当然这是一个问题,因为
.get()
方法仍然是“异步”的。您需要在
.then()
内部进行操作,或者类似地进行链操作。也就是说,下一行代码不等待前一行代码。您是对的。但是soneService.get()没有像Neil Lunn上面解释的那样返回值。
someService.get()
返回承诺,但该承诺是否解析为某个值取决于从http.get('app/file.json')返回的数据结构
。谢谢。我没有在service.ts中更改任何内容,而且我只按照您的建议在组件中添加了一行,而且效果很好。谢谢。
this.someService.get().then(a => {
  this.aArray = a;
  this.bArray = this.getBList(this.aArray); // Now `this.aArray` will have some value provided `someService.get()` returns something
});