简体   繁体   English

如何在Typescript构造函数中将数组对象转换为字符串?

[英]How to convert an array object to a string in typescript constructor?

Recently I started learning Angular 2 with basic knowledge on typescript. 最近,我开始学习有关打字稿的基本知识的Angular 2。 So, I tried to work out code using constructor. 因此,我尝试使用构造函数计算代码。 But I'm getting type error in the VS Code editor and also unable to get the expected output in the browser. 但是我在VS Code编辑器中遇到类型错误,并且也无法在浏览器中获得预期的输出。 I am sharing the code below and attaching the screenshot too. 我要分享下面的代码,并附上屏幕截图。 It would be very helpful if anyone tell me how to convert the Object in the Array to a string in the typescript constructor? 如果有人告诉我如何将数组中的对象转换为打字稿构造函数中的字符串,这将非常有用。

Here is the code: 这是代码:

import { Component } from '@angular/core';

import { Hero } from './hero';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title: string;
  heroes: Array<Hero>;
  myHero: string;

  constructor() {
    this.title = "Tour Of Heroes";
    this.heroes = [
      new Hero(1, 'Windstorm'),
      new Hero(13, 'Bombasto'),
      new Hero(15, 'Magneta'),
      new Hero(20, 'Tornado')
    ];
    this.myHero = this.heroes[0];
  }
}

Screenshot: VS Code Browser 屏幕截图: VS代码 浏览器


Author provided code copied from comment: 作者提供的从注释中复制的代码:

<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero}}</h2>
<p>Heroes:</p>
<ul>
  <li *ngFor="let hero of heroes"> {{ hero }} </li>
</ul>
this.myHero = this.heroes[0].name; // display the name

Or if you want to keep your selected hero as an object then display the name in the template. 或者,如果要保留所选英雄作为对象,则在模板中显示名称。

app.component.html app.component.html

{{myHero.name}}

As for the array you need to loop over it and display something interesting on the object from the array itself. 至于数组,您需要遍历它并在数组本身的对象上显示一些有趣的东西。

<div *ngFor="#hero of heroes">
  {{hero.name}}
</div>

From your comment, here is your fixed code that displays the name of the myHero instance and from loop over the heros array. 根据您的评论,这是固定的代码,它显示myHero实例的名称并在heros数组上循环。

<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero.name}}</h2>
<p>Heroes:</p>
<ul> <li *ngFor="let hero of heroes"> {{ hero.name }} </li> </ul>

You are assigning Hero class object(s) to string variable which is not compatible . 您正在将Hero类对象分配给不兼容的 字符串变量 So, rather than changing it to string , declare it with Hero class type . 因此,不要将其更改为字符串 ,而是使用Hero类type进行声明。 So, 所以,

myHero: string;

change it to 更改为

myHero: Hero;

And in template use it with property like, 并在模板中将其与诸如

<h1>{{title}}</h1>
   <h2>My favorite hero is: {{myHero.name}}</h2>
      <p>Heroes:</p>
         <ul>
             <li *ngFor="let hero of heroes"> {{ hero.name}} </li>
        </ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM