0

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

the page after refreshing displays:

{"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:

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

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

The server script is as follows:

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.

Dinesh Vishwakarma
  • 656
  • 3
  • 13
  • 34
user2129896
  • 307
  • 1
  • 7
  • 26
  • Check the [routing tutorial](https://angular.io/guide/router#appendix-locationstrategy-and-browser-url-styles), more specific, the location strategy, that might be your problem. – LordAlpaca Apr 02 '18 at 13:53
  • @LordAlpaca You can ask for more details. – user2129896 Apr 02 '18 at 14:13
  • Looks like you have /users/products routed to an api endpoint in the backend, instead of static index.html? Perhaps add a prefix to api routes, eg, /api/** ? – funkizer Apr 02 '18 at 15:46
  • @funkizer I do not know what you mean by adding the `api` prefix. You would give an example. I edited the question. I uploaded a server script – user2129896 Apr 03 '18 at 10:05

2 Answers2

0

answer:

I was editing the calling method on the server that retrieved data ('/api/user/products/:id')

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

and in product.service.ts I was editing the get method 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);
  }
user2129896
  • 307
  • 1
  • 7
  • 26
  • What are you getting here? this.productsService.getProducts(userid).subscribe(res => { this.products_ = res.data; console.log(data); }); – harold_mean2 Apr 04 '18 at 01:03
0

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

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

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

harold_mean2
  • 238
  • 1
  • 14