刷新后,页面无法加载-Angular [英] After refreshing, the page does not load - Angular

查看:104
本文介绍了刷新后,页面无法加载-Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刷新后,页面无法加载 http://localhost:4200/user/products/5ab425c6f5bff145304092f7

After refreshing, the page does not load http://localhost:4200/user/products/5ab425c6f5bff145304092f7

刷新后的页面显示:

{"success":true,"data":[{"_ id":"5ab548d8bea65e21c413766f","userid":"5ab425c6f5bff145304092f7","product_name":"Milck","product_type":"0","product_desc":"vvvvvv","__ v":0},{"_ id":"5aba43ef0a5c243330237bd5","userid":"5ab425c6f5bff145304092f7","product_name":"rolls","product_type":"0","product_desc:" rw," __ v:0},{" _ id:" 5abb6c5b9f076e2af0a3bbe3," userid:" 5ab425c6f5bff145304092f7," product_name:" xx," product_type:" 1," product_desc":"xx","__ v":0}]}

user-products.component.ts

@Component({
  selector: 'app-user-products',
  templateUrl: './user-products.component.html',
  styleUrls: ['./user-products.component.css']
})
export class UserProductsComponent implements OnInit {

  @Input()
  product: Product;

  user: User;
  UserType = UserType;

  product_name: string;
  product_type: ProductType;
  ProductType = ProductType;
  product_desc: string;

  produktForm: FormGroup;
  products: Product;
  userObj: any;
  expid: string;
  id: any;
  products_: any;

  constructor(private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private productsService: ProductsService,
    private authService: AuthService) { }

  ngOnInit() {

    this.userObj = this.authService.currentUser;
    const userid = this.userObj.userid;

     this.route.params.subscribe(params => {
      this.id =  params['id'];       
    });

    this.getProducts( this.id );

    this.produktForm = this.fb.group({
      product_name: this.product_name,
      product_type: this.product_type,
      product_desc: this.product_desc });

  }

  getProducts(userid) {
    console.log('getProducts userid ');
    console.log(userid);
    this.productsService.getProducts(userid).subscribe(res => {
      this.products_ = res.data;      
    });
  }
}

页面标题甚至都没有显示:

the page header is not even displayed:

app.component.html:

app.component.html:

< div class ="container">< app-navbar></app-navbar><路由器插座></路由器插座></div>

如何解决该错误?因此页面是在刷新后显示的.

How to fix the error? So the page was displayed after refreshing.

服务器脚本如下:

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app  = express();
var user = require('./routes/user.js');
var product = require('./routes/product.js');
const api = require('./server/api');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(require('body-parser').json({ type : '*/*' }));

app.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials");
  res.setHeader("Access-Control-Allow-Credentials", "true");
  next();
});

app.use(express.static(path.join(__dirname, 'dist')));

app.post('/register', user.signup);
app.post('/login', user.login); 
app.get('/user/:id', user.getuserDetails);
app.put('/user/:id', user.updateUser); 
app.post('/user/product/:id', product.saveproduct);
app.get('/users/products/', product.selectUsersProductsCount);
app.delete('/user/product/:id', product.deleproduct);

var apiRoutes = express.Router();
app.use('/api', apiRoutes);

app.get('/user/products/:id', product.selectproducts);  // method that returns data displayed after the page is refreshed
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

app.put('/user/product/:id', product.updateProduct);

const port = process.env.PORT || '4200'; // '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));

刷新页面后,服务器正确返回数据.

After refreshing the page, the server returns the data correctly.

推荐答案

这不是您问题的答案.我只是想澄清一下.你怎么来这里?

This is NOT an answer to your question. I am just trying to clarify it. What are you getting here?

getProducts(userid) {
  console.log('getProducts userid ');
  console.log(userid);
  this.productsService.getProducts(userid).subscribe(res => {
    this.products_ = res.data;      
    console.log(this.products); //Please provide data here.
  });
}

对不起,但是我不明白您要在此处显示的内容:

I am sorry, But I do not understand what your are trying to display here:

/user/products/userId

您是否要获取用户的购物车商品?如果是这样,您是否实现了商品/购物车类和用户类?下面的链接使您无需登录即可将产品添加到购物车.笔记.我只是使用数组进行演示.链接在这里.角度2从数组中删除重复的值

Are you trying to get cart items of the user? If so, have you implemented an Item/Cart Class and User Class? The link below allows you add products to a cart without signing on. Note. I am just using an array for demonstration only. Here is the link. Angular 2 remove duplicate values from an array

在我的应用中,当用户登录时.

In my app when the user is signed in.

 addItem(product: Product) {
  let item = new Item(product, 1, product.price, product.productId, '');
  const body = JSON.stringify(item);
  const token = localStorage.getItem('token');
  const headers = new Headers({'Authorization': token});
  headers.append('Content-Type', 'application/json');       
  const userId = localStorage.getItem('userId');
  console.log(item);
  return this._http.patch('http://localhost:3000/item/' + userId, body, {headers: headers})
    .map(response => response.json()) 
    .catch((err) => this.handleError(err)); 
  }

然后我可以循环我的cartItems并调用addItem.我保存令牌和userId.当用户注销时-localStorage.clear();

I can then loop my cartItems and call addItem. I save the token and userId. When the user logs out - localStorage.clear();

这篇关于刷新后,页面无法加载-Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆