如何在MEAN堆栈应用程序中从后端通信到前端?
我是MEAN Stack应用程序的新手,尝试将数据从服务器发送到前端时遇到了一些麻烦。但是,我确实正在进行一些通信,这仅仅是通过错误闪存消息。我的问题是希望以其他方式使用它,而不只是即兴消息。例如,如果用户没有会话,那么我希望他们导航回到登录页面。这是我尝试过但失败的。
服务器
// Middleware
const redirectLogin = ((req, res, next) => {
if (!req.session.user)
res.status(401).json({ loggedIn: false });
else
next();
});
// Route
router.route("/home").get(redirectLogin, (req, res) => {
Blog.find((err, docs) => {
if (err)
console.log(err);
else
res.json(docs);
});
});
前端
homePage() {
// Here is where I would like to say, If session, then true, else navigate(["/users/login"])
if (loggedIn === false)
this.router.navigate(["/users/login"])
else
// Success
return this.http.get(`${this.uri}/home`);
}
我发现通信的唯一方法是通过发送错误闪存消息,但除此之外没有其他。
回答如下:[您可以做的是调用api来检查用户是否已登录ngOnInit
生命周期挂钩,因此,每次加载组件时,您都可以检查会话是否存在于后端并相应地进行路由。
export class App implements OnInit{
constructor(){
//called first time before the ngOnInit()
}
ngOnInit(){
this.service.CheckLogin().subscribe(data=>{
if (data["loggedIn"] === false)
this.router.navigate(["/users/login"])
})
}
}
如何在MEAN堆栈应用程序中从后端通信到前端?
我是MEAN Stack应用程序的新手,尝试将数据从服务器发送到前端时遇到了一些麻烦。但是,我确实正在进行一些通信,这仅仅是通过错误闪存消息。我的问题是希望以其他方式使用它,而不只是即兴消息。例如,如果用户没有会话,那么我希望他们导航回到登录页面。这是我尝试过但失败的。
服务器
// Middleware
const redirectLogin = ((req, res, next) => {
if (!req.session.user)
res.status(401).json({ loggedIn: false });
else
next();
});
// Route
router.route("/home").get(redirectLogin, (req, res) => {
Blog.find((err, docs) => {
if (err)
console.log(err);
else
res.json(docs);
});
});
前端
homePage() {
// Here is where I would like to say, If session, then true, else navigate(["/users/login"])
if (loggedIn === false)
this.router.navigate(["/users/login"])
else
// Success
return this.http.get(`${this.uri}/home`);
}
我发现通信的唯一方法是通过发送错误闪存消息,但除此之外没有其他。
回答如下:[您可以做的是调用api来检查用户是否已登录ngOnInit
生命周期挂钩,因此,每次加载组件时,您都可以检查会话是否存在于后端并相应地进行路由。
export class App implements OnInit{
constructor(){
//called first time before the ngOnInit()
}
ngOnInit(){
this.service.CheckLogin().subscribe(data=>{
if (data["loggedIn"] === false)
this.router.navigate(["/users/login"])
})
}
}