Angular RouterLinks broken URL navigation unaffected - node.js

My angular router is failing to load the latest component after a router change is made within the application. If I call the URL manually it will load the correct content however any use of routerLink or a call to router.navigate has no affect on the router-outlet content.
I have tried binding to router events and recalling the getContent function when there is a change and this fixes the issue when calling programmatically.
The project is pretty bare but the router:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { ContentpaneComponent } from './contentpane/contentpane.component';
const routes: Routes = [
{ path: '', component: ContentpaneComponent },
{ path: 'post/:app', component: ContentpaneComponent }
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
And the container in app.component.html
<div class="above">
<app-sidebar></app-sidebar>
<div class="contentpane">
<router-outlet></router-outlet>
</div>
</div>
<app-terminal></app-terminal>
If there is any other code segments that would benefit please request in comments.
Here is the code containing the routerLink directives:
<div class="main">
<div class="logo">
O
</div>
<ul class="navbar">
<li *ngFor="let nav of navs">
<a routerLink="/{{nav.href}}" class="navitem">{{nav.title}}</a>
</li>
</ul>
</div>
EDIT: I am also getting a websocket error in the console:
WebSocket connection to 'ws://localhost:4200/sockjs-node/748/g0a4bxsw/websocket' failed: WebSocket is closed before the connection is established.
Not sure if it is a related issue.

So I managed to find the solution. The problem arose because routerLink does not force the reloading of a component when the URL changes, so ngOnInit does not get called. The fix I implemented was to subscribe my content update function to the route.params and queryParams events:
this.route.queryParams.subscribe(queryParams => {this.getContent()});
this.route.params.subscribe(queryParams => {this.getContent()});
This causes these functions to be called whenever the route updates.

Related

Why can React display an object but not its members?

I'm trying to wrap my head around the MERN stack. So far I've managed to query my database and get the data on an API endopoint, but I'm having some trouble getting it to show up on my front-end.
Here's my fronted code :
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component<{}, {res:any}> {
constructor(props:any) {
super(props);
this.state = {res: Array};
}
callAPI() {
fetch("http://localhost:5000")
.then(res => res.json())
.then(json => this.setState({res: json}));
}
componentWillMount() {
this.callAPI();
}
render() {
// WORKS
console.log(this.state.res[0]);
// DOESN'T WORK
console.log(this.state.res[0].name);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
)};
}
export default App;
As you can see it's just a modified version of the default React homepage. I just added a state and fetching data from my backend.
The problem comes when I try to console.log my data.
If I console.log(this.state.res[0]), everything is fine, and I get { "_id": "62207b47d40bca8ea8b60560", "name": "Patère", "checked": false, "links": [ "" ] } in my console. But if I try to only log the name, I get Uncaught TypeError: this.state.res[0] is undefined, which is weird, since it managed to display this.state.res[0] just fine before ?
What's causing this and how can I fix it ?
Thank you in advance.

Laravel jetstream inertia persistent layout

In a fresh laravel installation i'm trying to make layout persistent following the inertia doc https://inertiajs.com/pages
app.js
require('./bootstrap');
// Import modules...
import { createApp, h } from 'vue';
import { App as InertiaApp, plugin as InertiaPlugin } from '#inertiajs/inertia-vue3';
import { InertiaProgress } from '#inertiajs/progress';
import AppLayout from '#/Layouts/AppLayout';
const el = document.getElementById('app');
createApp({
render: () =>
h(InertiaApp, {
initialPage: JSON.parse(el.dataset.page),
resolveComponent: name => import(`./Pages/${name}`)
.then(({ default: page }) => {
if (page.layout === undefined) {
page.layout = AppLayout
}
return page
}),
}),
})
.mixin({ methods: { route } })
.use(InertiaPlugin)
.mount(el);
InertiaProgress.init({ color: '#4B5563' });
Dashboard.vue (here i replace the default app-layout wrapper by div)
<template>
<div>
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Dashboard
</h2>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
<welcome />
</div>
</div>
</div>
</div>
</template>
<script>
import Welcome from '#/Jetstream/Welcome'
export default {
components: {
Welcome,
},
}
</script>
While compiling i get this error :
Error: Codegen node is missing for element/if/for node. Apply
appropriate transforms first.
I can't figure out what that means. Is there a reason why the default laravel app with jetstream and inertia doesn't use persistent layout?
If the header slot is in AppLayout aka the persistent one, you cannot use this way (because there is no slot yet? I don't know but I know persistent layouts do mount after child components, this can be the culprit). As a solution, create another layout, ie PageLayout, with named slots and use that layout to build your dashboard and other pages:
AppLayout.vue
<template>
<div>Persistent stuff...</div>
<slot />
<div>Persistent stuff...</div>
</template>
PageLayout.vue
<template>
<slot name="header" />
<slot name="content" />
<div>PageLayout stuff...</div>
</template>
Dashboard.vue
<template>
<PageLayout>
<template #header>
<h1>Dashboard</h1>
</template>
<template #content>
<p>Welcome user!</p>
</template>
</PageLayout>
</template>
<script>
import AppLayout from 'AppLayout'
import PageLayout from 'PageLayout'
export default {
layout: AppLayout, // Persistent layout
components: {
PageLayout // Regular layout
}
</script>
There is an ongoing discussion here:
https://github.com/inertiajs/inertia/issues/171
You need the app-layout as you need to extend from it <template #header>

props can not be resolved in the render of a React class

I am getting started on webdevelopment with React and Node.js, all are new to me so I am following this tutorial: https://reactjs.org/tutorial/tutorial.html. I am using Visual Studio as IDE.
Everything seems to go as expected until I try to pass data through props. At that point "props" becomes flagged with an error "Cannot resolve symbol 'props'. I have googled myself silly trying to find a solution.
So far I have tried:
import React instead of declaring it as variable. Gives another error: Symbol 'React' cannot be properly resolved, probably it is located in inaccessible module
create a constructor. Gives another error: Call target does not contain any signatures.
Installed npm package for prop-types
I have posted my question to the relevant discord
So at this point I turn to you all, can you help me get going? See my code below:
declare var require: any;
var React = require('react');
var ReactDOM = require('react-dom');
//import * as React from "react";
//import * as ReactDOM from "react-dom";
//node_modules\.bin\webpack app.tsx --config webpack-config.js
class Square extends React.Component<any, any> {
//constructor() {
// super();
//}
render() {
return (
<button className="square">
{this.props.value}
</button>
);
}
}
class Board extends React.Component {
renderSquare(i) {
return <Square value={i}/>;
}
render() {
const status = 'Next player: X';
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
render() {
return (
<div className="game">
<div className="game-board">
<Board />
</div>
<div className="game-info">
<div>{/* status */}</div>
<ol>{/* TODO */}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);

Using reusable components in Vue 2 in comination with vue router

I seem to do something wrong when I'm trying to target child components in nested router-views with click events.
Current situation:
I have a component one and component two. Both have a child component called dialog.
Component one and two are being loaded through a router-view in parent component dashboard. Each view has a button to show their child component "Modal".
The button seems to work fine on the view that gets loaded on pageload. But as soon as I switch routes the showModal function does not know the dialog element from which view to target.
I thought the components would be destroyed and rebuilt upon switching routes but apparently not.
Here is my code, I hope someone is able to help:
App
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
/**
* First we will load all of this project's JavaScript dependencies which
* include Vue and Vue Resource. This gives a great starting point for
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap')
/**
* Next, we will create a fresh Vue application instance and attach it to
* the body of the page. From here, you may begin adding components to
* the application, or feel free to tweak this setup for your needs.
*/
Vue.component('vuetest', require('./components/vuetest.vue'))
const Dashboard = require('./components/dashboard.vue')
const FirstRoute = require('./components/firstroute.vue')
const Second = require('./components/secondroute.vue')
const routes = [
{
path: '/dashboard',
component: Dashboard,
children: [
{
path: 'firstview',
name: 'firstview',
canReuse: false,
component: FirstRoute
},
{
path: 'secondview',
name: 'secondview',
canReuse: false,
component: Second
}
]
}
]
const router = new VueRouter({
routes // short for routes: routes
})
window.EventHub = new Vue()
const app = new Vue({
el: '#app',
router
});
Vuetest
<template>
<div>
<h1>Vue Test</h1>
<router-view></router-view>
</div>
</template>
<script>
export default {
created() {
},
mounted() {
console.log('Component ready.')
}
}
</script>
Dashboard Route
<template>
<div>
<h1>Dashboard</h1>
<navigation></navigation>
<router-view></router-view>
</div>
</template>
<script>
Vue.component('navigation', require('./navigation.vue'))
</script>
Navigation
<template>
<div>
<router-link :to="{ name: 'firstview' }">first</router-link>
<router-link :to="{ name: 'secondview' }">second</router-link>
</div>
</template>
First Route
<template>
<div class="firstroute">
<h1>First Route</h1>
<button class="showmodal" v-on:click="showModal">Showmodal</button>
<modal></modal>
</div>
</template>
<script>
export default {
methods: {
showModal: function () {
EventHub.$emit('showModal')
}
}
}
Vue.component('modal', require('./modal.vue'));
</script>
Second Route
<template>
<div class="secondroute">
<h1>Second Route</h1>
<button class="showmodal" v-on:click="showModal">Showmodal</button>
<modal></modal>
</div>
</template>
<script>
export default {
methods: {
showModal: function () {
EventHub.$emit('showModal')
}
}
}
Vue.component('modal', require('./modal.vue'));
</script>
Modal
<template>
<div class="dialog hidden">
Dialog
</div>
</template>
<style>
.hidden {
display: none;
}
</style>
<script>
export default{
created() {
EventHub.$on('showModal', this.showModal);
},
methods: {
showModal: function() {
document.querySelector('.dialog').classList.toggle('hidden');
}
}
}
</script>
I really appreciate any help.
tiny recomendations
':class' directive instead of native code:
document.querySelector('.dialog').classList.toggle('hidden');
components:
import Modal from './modal'
export default {
...
components:
Modal
}
...
}
instead of
Vue.component('modal', require('./modal.vue'));
.. also Vuex is a good point for this case
additional:
https://github.com/vuejs/vue-devtools
https://jsfiddle.net/uLaj738k/2/
As it turns out the problem was the moment I called the querySelector method.
Assigning the .dialog element to a const in mounted() solved my problem.

Can I Create Nested Angular Component HTML Selectors?

Updated: Per Thierry Templier's response:
Below is essentially what I want to do, but unfortunately the inner components aren't rendering. Is there a way to nest components via their HTML selectors like so?
<custom-menu-bar-component (onCustomEvent)="handleEvent($event)">
<custom-button-component></custom-button-component>
<custom-dropdown-component></custom-dropdown-component>
</custom-menu-bar-component>
In my chrome debugger, I see only the outer component being rendered:
<custom-menu-bar-component>
<div class="row">
** Nothing here, where my two inner components should be :(
</div>
</custom-menu-bar-component>
And my components look like this:
CustomMenuBarComponent.ts:
import {Component} from 'angular2/core'
import {CustomButtonComponent} from './CustomButtonComponent'
import {CustomDropdownComponent} from './CustomDropdownComponent'
#Component({
selector: 'custom-menu-bar-component',
directives: [CustomButtonComponent, CustomDropdownComponent],
template: `
<div class="row"></div>
`
})
export class CustomMenuBarComponent {
}
CustomButtonComponent.ts:
import {Component, EventEmitter} from 'angular2/core'
import {CustomEvent} from './CustomEvent'
#Component({
selector: 'custom-button-component',
outputs: ['onCustomEvent'],
template: `
<button type="button" class="btn btn-light-gray" (click)="onItemClick()">
<i class="glyphicon icon-recent_activity dark-green"></i>Button</button>
`
})
export class CustomButtonComponent {
onCustomEvent: EventEmitter<CustomEvent> = new EventEmitter();
onItemClick(): void {
this.onCustomEvent.emit(new CustomEvent("Button Component Clicked"));
}
}
CustomDropdownComponent is nearly identical to the CustomButtonComponent, but with different text. I'm just trying to get this very simple example working before I start making these components more useful and reusable.
Is this kind of approach possible? I'm trying to make it easy for others to take these components and create more of my custom menu bars with ease and simplicity.
Not sure what your question is about but
<custom-menu-bar-component (onCustomEvent)="handleEvent($event)">
<custom-button-component></custom-button-component>
<custom-dropdown-component></custom-dropdown-component>
</custom-menu-bar-component>
requires <ng-content></ng-content> in the template of CustomMenuBarComponent
A bit of documentation can be found in https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#aftercontent I had expected a bit more this was all I found.
http://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html might contain some helpful information as well.
Update
Moving (onCustomEvent)="handleEvent($event)" to the <custom-button-component></custom-button-component> element should do what you want. Events from EventEmitter don't bubble.
In fact you have the error because you don't instantiate your EventEmitter in the CustomButtonComponent component:
#Component({
(...)
})
export class CustomButtonComponent {
onCustomEvent: EventEmitter<CustomEvent> = new EventEmitter(); // <-----
(...)
}
Otherwise your code seems correct.
Update
You need to use ng-content to include your sub components into the CustomMenuBarComponent one.
#Component({
selector: 'custom-menu-bar-component',
directives: [CustomButtonComponent, CustomDropdownComponent],
template: `
<div class="row">
<ng-content></ng-content>
</div>
`
})
export class CustomMenuBarComponent {
}

Resources