angular - Angular - 调用 API 重定向到另一个模块
问题描述
我有一个调用 rest api 的组件ngOnInit
。调用 api 重定向到另一个模块,但如果我不调用 api 则不会。
export class UserHomeComponent implements OnInit {
public postData = [];
constructor(
private anps: AddNewPostService,
) {
}
ngOnInit() {
this.getPost();
}
private getPost() {
this.anps.getPost().subscribe(
result => {
this.postData = result;
this.postData.forEach(value => {
value["images"] = "";
value['postText'] = value['postText'].replace(/(?:\r\n|\r|\n)/g, '<br>');
let content = "";
//Bold Data
var boldData = [];
boldData = value['postText'].split("**");
var num: number = 0;
let newBoldData = [];
boldData.forEach(res => {
if (num % 2 != 0) {
res = "<b>" + res + "</b>";
}
newBoldData.push(res);
num++;
});
newBoldData.forEach(res => {
content = content + "" + res;
});
this.content = content;
//Bold Data
//Italic Data
let italicContent = "";
var italicData = [];
italicData = content.split("*");
var num: number = 0;
let newItalicData = [];
italicData.forEach(res => {
if (num % 2 != 0) {
res = "<i>" + res + "</i>";
}
newItalicData.push(res);
num++;
});
newItalicData.forEach(res => {
italicContent = italicContent + "" + res;
});
this.content = italicContent;
//Italic Data
//Image Data
let imageContent = "";
var imageData = [];
imageData = this.content.split("![](");
var num: number = 0;
let newImageData = [];
imageData.forEach(res => {
let temp = res.split(")");
let temp1 = [];
let data = "";
temp.forEach(res => {
if (res.includes("https://")) {
value["images"] = res;
res = "<a href='" + res + "' target='_blank'/><img style='max-width: 100%;' src='" + res + "' /></a>";
}
temp1.push(res);
})
temp1.forEach(res => {
data = data + "" + res;
})
newImageData.push(data);
num++;
});
newImageData.forEach(res => {
imageContent = imageContent + "" + res;
});
this.content = imageContent;
value['postText'] = this.content;
//Image Data
})
},
error => { console.log(error); }
)
}
}
这里UserHomeComponent
在UserModule
. 我的问题是,每当我将getPost()
方法放在ngOnInit
方法上时,它都会被重定向到另一个模块。我怎么解决这个问题?
getPost()
方法是这样的
public getPost() {
return this.http.get(this.apiUrl).catch(error => { return this.handleError.handleError(error) });
}
请帮帮我!
解决方案
只用这个,
public getPost() {
return this.http.get(this.apiUrl);
}
试试看。
您应该尝试使用 promise 然后捕获而不是订阅。如果订阅了,那么您应该销毁,但这与重定向无关。
推荐阅读
- php - 从 Laravel 8 工厂访问模型方法 - ErrorException: Attempt to read property on null
- c - 为什么这个“for循环”有效而不是溢出
- mongodb - MongoDB groupby - 在字段中提取逗号分隔值
- python - Python 中的关键错误,使用 Pycharm 和 Pandas
- react-native - 前端基于OAUTH2获取社交登录中的访问令牌不是很危险吗?
- javascript - 无法使用 fetch 解决承诺
- laravel - 如何从 laravel-8 的另一个表中的表中调用 id
- java - 如何在单独的线程中执行 HTTP 请求并返回响应
- java - 如何将自定义 Http 客户端注入 Spring Cloud openfeign?
- c# - 具有自定义图像和文本在运行时更改的 RadioButton