刷新后,页面无法加载 - Angular

时间:2018-04-02 13:46:46

标签: angular

刷新后,页面无法加载 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}]}

用户-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;      
    });
  }
}

页面标题甚至没有显示:

app.component.html:

<div class="container"> <app-navbar></app-navbar> <router-outlet></router-outlet> </div>

如何修复错误?因此刷新后显示页面。

服务器脚本如下:

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}`));

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

2 个答案:

答案 0 :(得分:0)

<强>答案:

我正在编辑检索数据('/api/user/products/:id'

的服务器上的调用方法

app.get('/api/user/products/:id', product.selectproducts);

在product.service.ts中我正在编辑get方法http://localhost:4200/api/user/products/${userid}

 getProducts(userid) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', `${this.jwtToken}`);
    let options = new RequestOptions({ headers: headers });

    return this.http.get(`http://localhost:4200/api/user/products/${userid}`, options)
      .map((response: Response) => response.json())
      .catch(this.handleError);
  }

答案 1 :(得分:0)

这不是你问题的答案。我只想澄清一下。你在这里得到什么?

for

对不起,但我不明白你想在这里展示什么:

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.
  });
}

您是否想要获取用户的购物车商品?如果是这样,您是否实施了项目/购物车类和用户类?以下链接允许您在不登录的情况下将产品添加到购物车。注意。我只是使用数组进行演示。链接在这里。 Angular 2 remove duplicate values from an array

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

/user/products/userId

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