【问题标题】:Angular - Why my variable is "undefined" after subscribe to API?Angular - 为什么我的变量在订阅 API 后是“未定义的”?
【发布时间】:2020-02-29 08:32:27
【问题描述】:

调用我的 API 服务后,我的模板中有一个未定义的变量,但我在控制台中看到了预期的结果。

我的 VideoComponent 调用了 API

export class VideoComponent implements OnInit {
  video: Video = new Video();

  constructor(private apiService: ApiService, private route: ActivatedRoute) {
  }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.apiService.getOneVideoByID(params['id']).subscribe((video: Video) => {
        this.video = video;
        console.log(this.video);
      });
    });
  }
}

有我的 API 服务:

export class ApiService {
  PHP_API_SERVER = 'http://127.0.0.1/TutoWorld/backend/api';
  private headers;

  constructor(private httpClient: HttpClient) {
    this.headers = new HttpHeaders().set('Content-Type', 'application/json')
  }


  getOneVideoByID(id: number): Observable<Video> {
    return this.httpClient.get<Video>(`${this.PHP_API_SERVER}/readOne?id=${id}`,{headers: this.headers});
  }
}

我的模板:

<div class="block5"></div>
<div id="videoContainer">
  <p>video title: {{video.titre}}  </p>
</div>

还有我的视频模型:

export class Video {
  id: number;
  url: string;
  titre: string;
  langue: string;
  description: string;
  date_creation: string;
  date_ajout: string;
  auteur_id: number;
  auteur_nom: string;
}

如果有人可以帮助我解决这个问题,那就太好了。
谢谢

【问题讨论】:

  • 什么是未定义的? console.log(this.video)?
  • 不,当我尝试在模板中访问时:

    视频标题:{{video.titre}}

    。在 console.log 我看到了很好的结果
  • 嗯...这很奇怪。如果你做&lt;p&gt;video: {{ video | json }} &lt;/p&gt;. And do you see video title: `出现在视图中,你会看到什么?
  • 添加管道时没有任何变化。我的页面有截图:zupimages.net/up/20/09/6xay.png
  • 我建议您将该定义转换为 interface 而不是 class。您没有使用构造函数,并且接口不会在 javascript 中转译。

标签: angular api subscribe


【解决方案1】:

看控制台,好像是个数组。

我也会避免嵌套订阅,试试这个:

  import { switchMap } from 'rxjs/operators'; // this import could be wrong, double check
.....
  ngOnInit() {
    this.route.params.pipe(
      switchMap(params => this.apiService.getOneVideoByID(params['id'])),
    ).subscribe((video: Video) => {
      this.video = video[0];
      console.log(this.video);
    });
  }

【讨论】:

  • 我有这个错误:TS2339:属性 'subscribe' 在类型 'OperatorFunction' 上不存在。
  • 我忘记了开关图上的结束括号,现在检查
  • 太好了,它正在工作,但我的 html 中有一个
【解决方案2】:

谢谢,它正在工作,但我的 html 中有一个,现在我有另一个错误消息:https://zupimages.net/up/20/09/cik2.png

有我的 iframe 代码:

<iframe width="1280" height="720"
          src="https://www.youtube.com/embed/{{getVideoID(video.url) | safe}}"
          frameborder="0"
          allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
          allowfullscreen>
  </iframe>

还有我的 GetVideoID 代码:

getVideoID(url: string) {
    return this.apiService.youtube_parser(url);
  }


  youtube_parser(url) {
    let regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
    let match = url.match(regExp);
    return (match && match[7].length == 11) ? match[7] : false;
  }

管道代码:

import {Pipe, PipeTransform, SecurityContext} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }
  transform(url) {
    return this.sanitizer.sanitize(SecurityContext.URL, url)
  }
}

【讨论】:

  • 得到 2:“无法读取未定义的属性‘匹配’”和“资源 URL 上下文中使用的不安全值”。你可以在截图上看到它
  • 我认为第一个是正常的:需要时间从 api 获取 url 但我不明白第二个值不安全
  • stackoverflow.com/questions/60456881/… 也许将其更改为 [src] = "url | safe" 并将 url 分配给嵌入的 youtube URL。
  • 感谢它有效,但我也必须通过以下方式更改我的 SafePipe 类的返回:“return this.sanitizer.bypassSecurityTrustResourceUrl(url);”现在好了。谢谢
【解决方案3】:

要在这里回答最初的问题,我必须说您将来自数组的 API 响应视为单个实例。这就是为什么你得到它 undefined :)

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 2021-02-16
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多