无法使用订阅的数据

时间:2018-10-31 18:30:18

标签: javascript angular typescript

我在mongo中有一个收藏,里面有很多这样的文件:

{
  name: "someUniversityName",
  campus: ["someCity", "anotherCity", "anotherCity2"]
}

我想发出GET请求并获取它们。 完成,并在我的终端中正确显示了201 res.status。正如您在下面的代码中看到的那样,我是使用subscribe中的doIt()的{​​{1}}所做的。

我无法执行的操作是:仅将我所提取大学中的helper.service.ts属性分配给name中的变量。 然后,我可以将这些值分配给:

universities.component.html

更新1

我来自html文件的console.log <select name="universidad" class="form-control" id="univer" (click)="doIt()"> <option *ngFor="let univ of univs"> {{ univ }} <-- DISPLAY THEM HERE --> </option> </select> this.universidadname属性是sede,这意味着应该在{{1}中完成分配}至undefined尚未完成?


我的代码

universities.component.ts

.subscribe

helperService.ts

this.universidad

html视图

import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { map } from '../../../../../../../node_modules/rxjs/operators';
import { HelperService, universidad } from "../../../../../services/helper.service";
import { Observable } from '../../../../../../../node_modules/rxjs';


@Component({
  selector: 'app-usuarios',
  templateUrl: './usuarios.component.html',
  styleUrls: ['./usuarios.component.scss']
})
export class UsuariosComponent implements OnInit {
  universidad: Object = {
    name: String,
    sede: [String]
  }
  universidadModel: String

  constructor(
    private http: HttpClient,
    private helperService: HelperService
  ) { }


  doIt(){
    this.helperService.getListado()
      //clone the data object, using its known config
      .subscribe((data: universidad) => this.universidad = {
        name: data['name'],
        sede: data['sede']
      });
  }

  ngOnInit() {

  }
}

致谢。

1 个答案:

答案 0 :(得分:0)

解决了。我在ngOnInit中编写了此代码,因此它需要初始化。我只需要遍历请求返回我的objets数组中的对象。 universidadListado只是一个接收名称的数组,因此我可以使用*ngFor遍历它们。

this.http.get('http://localhost:3000/universidads/listado')
      .subscribe(res => {
        for(let key in res){
          this.universidadListado.push(res[key].name)
        }
      })

现在,我的select将所有大学的名称动态显示为options

感谢您的帮助, 问候。

相关问题