如何在角度6中推入带有两个参数的对象?

时间:2018-09-18 23:52:02

标签: angular typescript

我一直在关注angular tour of heroes教程,并且正在使用progressToBackCheckMedianString = $"{newLine} Medians {(medianInProgressFormattedTime != string.Empty ? $"{newLine} {medianInProgressFormattedTime}{newLine}" : string.Empty)}"; Http部分。我一直在尝试使用代码,我想知道如何使用两个参数推送对象。

我想推送一个带有名称和年份的对象(当前在hero.component.ts中硬编码为2017)并将其添加到列表中。

in-memory-data.service.ts

InMemoryDBService

hero.service.ts

import { InMemoryDbService } from 'angular-in-memory-web-api';

export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const heroes = [
      { id: 1, name: 'Chuck Norris', year: 2019 },
      { id: 2, name: 'Donald Duck', year: 2019 },
      { id: 3, name: 'Ash Catchem', year: 2019 },
      { id: 4, name: 'Morgan Freeman', year: 2019 },
      { id: 5, name: 'Luke Skywalker', year: 2019 },
      { id: 6, name: 'Bob Ross', year: 2018 },
      { id: 7, name: 'Sherlock Homes', year: 2018 },
      { id: 8, name: 'Bugs Bunny', year: 2018 },
      { id: 9, name: 'Edgar Poe', year: 2018 },
      { id: 10, name: 'Barack Obama', year: 2018 }
    ];
    return {heroes};
  }
}

}

hero.component.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable, of } from 'rxjs';

import { Hero } from './hero';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class HeroService {

  private heroesUrl = 'api/heroes';  // URL to web api

  constructor(private http: HttpClient) { }
  /** GET heroes from the server */
  getHeroes(): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
  }

  /** POST: add a new hero to the server */
addHero (hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(this.heroesUrl, hero, httpOptions);
}

hero.component.html

import { Component, OnInit } from '@angular/core';
import { HeroService } from '../hero.service';
import { Hero } from '../hero';


@Component({
  selector: 'app-hero',
  templateUrl: './hero.component.html',
  styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {

  heroes: Hero[];
  year: number = 2017;

  constructor(private heroService: HeroService) { }

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroService.getHeroes()
    .subscribe(heroes => this.heroes = heroes);
  }

  add(name: string): void {
    name = name.trim();
    if (!name) { return; }
    this.heroService.addHero({ name } as Hero)
      .subscribe(hero => {
        this.heroes.push(hero);
      });
    }

}

因此,我知道我必须向html组件中添加参数,例如: <div *ngFor="let hero of heroes"> <span class="badge">{{hero.id}}</span> {{hero.name}} {{hero.year}} </div> <br> <div> <label>Hero name: <input #heroName /> </label> <!-- (click) passes input value to add() and then clears the input --> <button (click)="add(heroName.value); heroName.value=''"> add </button> </div> ,然后还必须在components.ts和service.ts内部添加参数,但是我不确定到底该如何更改我的需求,这是我的最佳尝试:

<button (click)="add(heroName.value, year); heroName.value=''">

但是,在点击添加按钮后,年份并没有添加,这是我需要帮助的地方。

3 个答案:

答案 0 :(得分:1)

您有一个看起来像这样的课:

export class Hero {
  id: number;
  name: string;
  year: number;
}

如果要创建一个新的hero类型的Object,则将其推入数组。

add(name: string, year: number) {
   const hero = new Hero (this.heroes.length++, name, year);
   //the rest of your code 
   this.getHeroes(); //this will pull the updated list of heroes  
}

我要传递的第一个参数是数组的长度+ 1,以便动态为其赋予ID和ID。

答案 1 :(得分:1)

向函数添加一个额外的参数,并向按钮发出的函数添加另一个参数。

hero.component.ts

add(name: string, year: number): void {
    name = name.trim();
    if (!name) { return; }
    this.heroService.addHero({ name, year } as Hero)
      .subscribe(hero => {
        this.heroes.push(hero);
      });
    }

hero.component.html

<button (click)="add(heroName.value, year); heroName.value=''">
      add
    </button>

答案 2 :(得分:0)

更改此

<button (click)="add(heroName.value, year); heroName.value=''">

对此

<button (click)="add(heroName.value, hero.year); heroName.value=''">

“年份”不引用任何内容,而“ hero.year”实际上访问ngFor =“让英雄英雄”的各个元素。