如何解决在我的 Angular 应用程序中对 JokeAPI 的 API 调用进行观察/订阅时遇到问题
我现在已经花了 3 天的大部分时间在这上面,我只知道这将是一件愚蠢的事情。 我的 api 调用正常工作,我收到了响应,但我的 ngFor 循环让我头疼这个错误:
你可以看到我的API在图片底部返回了一个数据包。我使用在 home 组件中加载 fin 的标准 div 测试了该组件,所以我知道这不是问题。据我所知,尽管我使用的是观察和订阅,但看起来 ngFor 循环正在尝试在调用返回的数据之前运行。 这是我的打字稿文件:
//joke.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({providedIn: 'root'})
export class JokesService {
//service api
apiURL = 'https://v2.jokeapi.dev/joke/';
constructor(private http: HttpClient) {}
//optional filters
numJokes = 10;
//add more than one category using comma separation
categories = 'Programming'; //options: Programming,Misc,Dark,Pun,Spooky,Christmas or 'Any' for all categories
//add more than one flag using comma separation
blacklistFlags = 'nsfw,racist,sexist,explicit'; //options: explicit,nsfw,political,religIoUs,sexist
getJokes() {
function getTypeName(val) {
return {}.toString.call(val).slice(8,-1);
}
return this.http
.get(`${this.apiURL}${this.categories}?blacklistFlags=${this.blacklistFlags}&amount=${this.numJokes}`)
.pipe(map(data => {
const jokesArr = [];
for (let i=0; i<10; i++) {
jokesArr.push(data['jokes'][i]);
}
return jokesArr;
}))
.subscribe(data => console.log("Payload = ",getTypeName(data),data));
}
}
//joke-scroll.component.ts
import { Component,OnInit } from '@angular/core';
import { JokesService } from '../../../jokes.service';
@Component({
selector: 'app-joke-scroll',templateUrl: './joke-scroll.component.html',styleUrls: ['./joke-scroll.component.sass']
})
export class JokeScrollComponent implements OnInit {
jokesArr;
constructor(private jokesService: JokesService) { }
ngOnInit(): void {
this.jokesArr = this.jokesService.getJokes();
console.log(this.jokesArr);
}
}
//joke-scroll.component.html
<div class='Box scrollingText' *ngFor="let joke of jokesArr">
<p *ngIf=""></p>
<p *ngIf="joke.type == 'twopart'"> Q: {{ joke.setup }} A: {{ joke.delivery }}</p>
<p *ngIf="joke.type == 'single'"> {{ joke.joke }} </p>
</div>
任何帮助将不胜感激。
解决方法
订阅服务不是一个好主意。最好是做组件。您也可以更自由地对其进行自定义。如果您想修复上述代码,您可能可以使用 async await,但仍然不推荐使用。
,我能够通过绑定数据并在服务调用开始时删除返回命令来解决该问题。将管道函数留在服务调用中,根据需要返回数据。这是我更新的代码:
[SecurityHeaders]
[AllowAnonymous]
public class UserInfoController : Controller
{
private readonly AppDbContext _context;
public UserInfoController(AppDbContext context)
{
_context = context;
}
// GET: UserInfo
public async Task<IActionResult> Index()
{
return View(await _context.PersistentGrant.ToListAsync());
}
}
现在我只需要修复它,这样我就会得到一行 10 个滚动笑话,而不是 10 行单个滚动笑话。谢谢小伙伴的建议。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。