Angular订阅的可观察对象在视图上不显示信息。

huangapple go评论63阅读模式
英文:

Angular suscribed observable don't showing information on the view

问题

我遇到了在进行Angular的"Tour Of Heroes"教程的第六步时出现问题,教程中要从服务器获取数据,但我不是使用模拟数据服务器,而是使用了一个基于Node.js Express和MySQL的API。

问题出现在我尝试显示英雄详细信息(通过ID获取一个英雄)时,一切似乎正常,但信息没有显示在视图中。

模板:

<div *ngIf="hero">
    <h2>{{ hero.name }} Details</h2>
    <div>id: {{hero.id}}</div>
    <div>
        <label for="name">Hero name: </label>
        <input id="name" [(ngModel)]="hero.name" placeholder="name">
    </div>
    <button type="button" (click)="goBack()">go back</button>
</div>

组件:

ngOnInit(): void {
    this.getHero();
}

getHero(){
    const id = Number(this.route.snapshot.paramMap.get("id"));
    this.heroService.getHero(id).subscribe(hero => {
        this.hero = hero;
        console.log("hero", hero)
    })
}

服务:

private heroesUrl = 'http://localhost:3300/api/';

constructor(private MessageService: MessageService, private http: HttpClient) { 
}

private log(message: string) {
    this.MessageService.add(`HeroService: ${message}`);
}

getHeroes(): Observable<Hero[]>{
    this.log('HeroService: fetched heroes');
    return this.http.get<Hero[]>(this.heroesUrl);
}

getHero(id: number): Observable<Hero> {
    const url = `${this.heroesUrl}${id}`;
    return this.http.get<Hero>(url);
}

我不知道问题出在哪里,我正在学习Angular,但是Observable已经成功订阅了。在附加的图片中,您可以看到控制台中至少API是正常工作的。

英文:

image of the detail view with console to see the console.log()
I'm having troubles making the Tour Of Heroes Angular tutorial work, i'm in the 6 step of the tutorial, getting the data from a server but instead of getting the data from a simulated data server i have a api with nodejs express and mysql.

The problem cames when i try to show the detail of the hero (fetching one by id), all seems to work but the information don't show on the view.

template:

&lt;div *ngIf=&quot;hero&quot;&gt;
    &lt;h2&gt;{{ hero.name }} Details&lt;/h2&gt;
    &lt;div&gt;id: {{hero.id}}&lt;/div&gt;
    &lt;div&gt;
        &lt;label for=&quot;name&quot;&gt;Hero name: &lt;/label&gt;
        &lt;input id=&quot;name&quot; [(ngModel)]=&quot;hero.name&quot; placeholder=&quot;name&quot;&gt;
    &lt;/div&gt;
    &lt;button type=&quot;button&quot; (click)=&quot;goBack()&quot;&gt;go back&lt;/button&gt;
&lt;/div&gt;

component:

ngOnInit(): void {
    this.getHero();
  }

  getHero(){
    const id = Number(this.route.snapshot.paramMap.get(&quot;id&quot;));
    this.heroService.getHero(id).subscribe(hero =&gt; {
      this.hero = hero;
      console.log(&quot;hero&quot;, hero)
    })
  }

service:

  private heroesUrl = &#39;http://localhost:3300/api/&#39;;

  constructor(private MessageService: MessageService, private http: HttpClient) { 
  }

  private log(message: string) {
    this.MessageService.add(`HeroService: ${message}`);
  }
  
  getHeroes(): Observable&lt;Hero[]&gt;{
    this.log(&#39;HeroService: fetched heroes&#39;);
    return this.http.get&lt;Hero[]&gt;(this.heroesUrl);
  }


getHero(id: number): Observable&lt;Hero&gt; {
  const url = `${this.heroesUrl}${id}`;
  return this.http.get&lt;Hero&gt;(url);
}

I don't know what's the problem, im learning angular but the observable is well suscribed, in the attached image you can see in the console that at least the api is working.

答案1

得分: 0

你收到了一个包含唯一元素的数组,在控制台中看到了 [``]。所以在订阅中,你可以写成 hero[0]

在你的服务中,你也可以返回数组的第一个元素。为此,使用rxjs/operator的map方法。

请注意,尽管你告诉Angular getHero 返回一个 Observable<Hero>,但实际上你得到的是一个 Observable<Hero[]>。是的,当我们指示函数的返回类型时,这并不会让我们“神奇地”获得结果,它只是帮助我们编写代码,并且编辑器会为我们提供建议。

英文:

you received an array with an unique element, see the [``] in console. So

Or in subscribe your write hero[0]

  this.heroService.getHero(id).subscribe(hero =&gt; {
      this.hero = hero[0];
    })

Or in your service return the first element of the array. For this use rxjs/operator map

getHero(id: number): Observable&lt;Hero&gt; {
  const url = `${this.heroesUrl}${id}`;
  return this.http.get&lt;Hero[]&gt;(url).pipe(
        map((res:Hero[])=&gt;res[0])
      );
}

See that although you say to Angular that getHero return an Observable&lt;Hero&gt; really you got an Observable&lt;Hero[]&gt;. Yes, when we indicate the return of a function this not make "magically" we get the result, only help us to write the code and the editor advise us about it

huangapple
  • 本文由 发表于 2023年1月5日 03:04:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75010098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定