使用angular 2和typescript在数组中按id查找对象

时间:2017-05-09 09:27:24

标签: arrays angular typescript

大家好我正在使用asp.net mvc 5.
当我尝试通过id查找对象时,它返回undefined。当我执行console.log(this.vtypes)时,这些对象显示正常。

controller.cs:

public JsonResult GetVerificationType(){
        List<verificationType> vlist = new List<verificationType>();
        vlist.Add(new verificationType() { vType = "vtype1", vtypeID = 1 });
        vlist.Add(new verificationType() { vType = "vtype2", vtypeID = 2 });
        vlist.Add(new verificationType() { vType = "vtype3", vtypeID = 3 });
        return Json(vlist, JsonRequestBehavior.AllowGet);}

打字稿文件:

export class DashboardComponent implements OnInit {
model: any = {};
vtypes = [];
constructor(private LoginServiceModule: LoginService, private router: Router, ) { }

ngOnInit() {
    this.LoginServiceModule.getVerificationTypes().subscribe(x => {
        for (let i = 0; i <= x.length - 1; i++) {
            this.vtypes.push(x[i]); <--- x[i].vtypeID doesn't work here
        }
    });
    console.log(this.vtypes); <----- works fine shows array of 3 length
    var item = this.vtypes.find(x => x.vtypeID === 1);
    console.log(item); <---- returns undefined even when vtypeID = 1 is present
}}

1 个答案:

答案 0 :(得分:0)

您需要在订阅

中移动异步逻辑
 this.LoginServiceModule.getVerificationTypes().subscribe(x => {
        for (let i = 0; i <= x.length - 1; i++) {
            this.vtypes.push(x[i]); <--- x[i].vtypeID doesn't work here
        }
        console.log(this.vtypes); <----- works fine shows array of 3 length
        var item = this.vtypes.find(x => x.vtypeID === 1);
        console.log(item);
    });

建议阅读:How do I return the response from an Observable/http/async call in angular2?