尽管有 ngOnInit,但我的可观察值没有显示

My observable value is not displayed despite the ngOnInit

首先,我为我的英语一点不好而道歉。我今天请求你的帮助,因为我有一个难以理解的问题!

我目前正在 Angular 并使用 .subscribe 来跟踪我的可观察对象。 这是我的组件:

export class SiteDetailComponent implements OnInit {

public test1 : ISite = <ISite>{};
public test2: ISite[] = [];

public errMsg : string = "";
constructor(...)


ngOnInit() {
const id : number = Number(this.route.snapshot.paramMap.get('id'));

this.SiteListeService.getSiteById(id).subscribe({
  next: site => {
    this.test1 = site;
  },
  error: err => this.errMsg = err
});

this.SiteListeService.getSites().subscribe({
  next: sites => {
    this.test2 = sites;

  },
  error: err => this.errMsg = err
});

如你所见,我在 2 Observable 上创建了一个 .subscribe:this;SiteListeService.getSites() 和 this.SiteListeService.getSiteById(id),这是相关的服务(我已经导入了构造函数) .

public getSites(): Observable<ISite[]> {
return this.http.get<ISite[]>(this.HOTEL_API_URL + "test/").pipe(
  tap(test2 => console.log('test2 : ', test2)),
  catchError(this.handleError)
);
}

public getSiteById(id : number): Observable<ISite> {
  return this.http.get<ISite>(this.HOTEL_API_URL + "test/" + id).pipe(
    tap(test1 => console.log('test1 : ', test1)),
    catchError(this.handleError)
  );
}

问题是我在 .html 中使用的 test1 变量不想显示,这里是示例:

<h5 class="card-title">{{ test1.nom }} </h5>

另一方面,我在同一个 .html 中使用的 test2 变量有效,例如:

<div class="col mb-4" *ngFor="let t2 of test2">
<h5 class="card-title">{{ t2.nom }}</h5>

我不明白为什么一个显示一个不显示!但是,我将两者都放在 ngOnInit() 中,以便优先处理它!

在我的服务中,我对我的 https return 请求 console.log 做了一个 console.log,一切正常... 这是 google chrome 控制台向我显示的内容:

希望我已经为您提供了所有必要的信息,如果我的话不正确,请原谅我不是专业人士。预先感谢您的阅读!

假设当您从消息中获取日志条目时服务方法 getSiteById 在第 30 行,http 请求是 return 数组:

您的函数需要一个对象。因此,当您在此处分配变量 test1 时:

   this.test1 = site;

它变成了一个只有一个元素的数组。

有几个选项可以解决这个问题:

  1. 改变它以获得第一个元素
   this.test1 = site[0];
  1. 这也可以在服务功能中完成
public getSiteById(id : number): Observable<ISite> {
  return this.http.get<ISite[]>(this.HOTEL_API_URL + "test/" + id).pipe(
    map(data => data[0]),
    catchError(this.handleError)
  );
}
  1. 为此请求更改您的后端,使其成为 return 元素而不是数组。