Pass query string from index.html to Angular2 component - angular2-routing

I need some help in accessing query string from index.html in Angular2 component. I have followed this link but it did not work for me
link
my index.html
<!doctype html>
<html>
<head>
<base href="/">
<!-- css importd -->
</head>
<body>
<app-root>Loading .. </app-root>
</body>
</html>
app.component.ts
...
public constructor(private activatedRoute:ActivateRoute) {}
ngOnInit() {
this.activateRoute.queryParams.subscribe((params:Params) => {
console.log(params['code']);
});
}
And I am invoking url http://localhost:8080/?code=test

Try this:
constructor(private route: ActivatedRoute) { }
ngOnInit() {
// get param
let paramcode = this.route.snapshot.queryParams["code"];
}

Try this :-
this.activateRoute.queryParams.subscribe(queryParams =>
console.log(queryParams['code']);
);
Add your html is code :-
<router-outlet></router-outlet>

Related

Google font loads very weirdly after the deployment to the vercel

I have deployed the next js app to the server using vercel. I have referenced the two google fonts in _document.js. While I am running the app locally both font load without any problem.
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document
{
static async getInitialProps(ctx)
{
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render()
{
return (
<Html>
<Head>
<link href="https://fonts.googleapis.com/css2?family=Crete+Round&family=Work+Sans:wght#500;600&display=swap" rel="stylesheet" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
index.js
import Head from "next/head";
import Script from "next/script";
import Banner from "../components/Banner";
import { fetchAPI } from "../lib/api";
import Articles from "../components/Articles";
export default function Home({ articles })
{
return (
<>
<Head>
<title>Life Sciencify - Explore the mystery of life with Science! </title>
</Head>
<Articles articles={articles} />
</>
);
}
export async function getServerSideProps()
{
const [articlesRes] = await Promise.all([
fetchAPI("/posts", { populate: ["cover", "category"] })
]);
console.log(articlesRes)
return {
props: {
articles: articlesRes.data
}
};
}
app.js
import Script from "next/script";
import "bootstrap/dist/css/bootstrap.css";
import "../styles/globals.css";
import { useEffect } from "react";
import Header from "../components/Header";
import SearchBlock from "../components/SearchBlock";
import Footer from "../components/Footer";
function MyApp({ Component, pageProps })
{
useEffect(() =>
{
import("bootstrap/dist/js/bootstrap");
}, []);
return (
<>
<Component {...pageProps} />
</>
);
}
export default MyApp;
After the deployment it is showing the weird behavior.
Initially When I am in the home page the page doesn't load any font.
Now, when I click the link Post1 or Post 2, it will be redirected to the detail page.
at first font is not loaded in this page too.
Now, after the page refresh the font gets loaded.
Now, when I go to the back page in the browser, the home page will have the font loaded. But again when the page is refreshed the font will be gone.
What is the causing the weird behavior?
I am running the application in the next js version of "12.1.6".
Referenced:
google-font-display
font-optimization
In the _document.js i used two google fonts separately and it is working now.
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document
{
static async getInitialProps(ctx)
{
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render()
{
return (
<Html>
<Head>
<link href="https://fonts.googleapis.com/css2?family=Work+Sans:wght#500;600&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Crete+Round&display=swap" rel="stylesheet" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
and in index.js, change server side rendering to static props:
export async function getStaticProps()
{
const [articlesRes] = await Promise.all([
fetchAPI("/posts", { populate: ["cover", "category"] })
]);
console.log(articlesRes)
return {
props: {
articles: articlesRes.data
}
};
}
After this changes I deployed to vercel it worked fine, again after some time i changes to getServerSideProps, it was not working. So, the culprit was getServerSideProps with google font.

How to add Tailwind CSS scroll-smooth class to Next.js

I want to add scroll behaviour smooth to my Next.js app, and the Tailwind CSS documentation instructs us to add the utility class in <html/>.
<html class="scroll-smooth ">
<!-- ... -->
</html>
This file does not contain an html tag:
import Head from "next/head";
import "#material-tailwind/react/tailwind.css";
import "../styles/globals.css";
function MyApp({ Component, pageProps }) {
return (
<>
<Head>
<link
href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet"
/>
</Head>
<Component {...pageProps} />
</>
);
}
export default MyApp;
How and where can I add the smooth-scroll utility class in my project?
The simplest solution, do it from your globals.css file...
#tailwind base;
#tailwind components;
#tailwind utilities;
#layer base {
html {
#apply scroll-smooth;
}
}
Use a custom _document.js and add it there - Here is an explanation of what it does -
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render() {
return (
<Html class="scroll-smooth">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
For those who will be using nextjs 13 . You can simply add the class (clasName) in the parent layout file like below :-
import '../styles/globals.css'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html className='scroll-smooth'>
<head />
<body>{children}</body>
</html>
)
}

How to create dynamic route for top-level page in NEXT?

To support these URLs:
/account?tab=profile
/account?tab=pass
/account?tab=points
I know that I can change them to:
/account/profile
/account/pass
/account/points
And then create this route:
/pages/account/[tab].js
But this means that the accoun is a directory, not a file.
I want to have a account.js top-level file, and have a route for query strings on it.
I don't know how to do it. Something like /account?[tab] route. Is it possible?
import type { GetServerSideProps, NextPage } from 'next'
import Head from 'next/head'
import { ParsedUrlQuery } from 'querystring';
import styles from '../styles/Home.module.css'
const About: NextPage<{ query: ParsedUrlQuery }> = ({ query }) => {
console.log(query);
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1>About</h1>
</main>
</div>
)
}
export const getServerSideProps: GetServerSideProps = async ({ query }) => {
return {
props: {
query
}
}
}
export default About

trouble rendering view in deno/oak

I'm using deno, oak, and view_engine.
Here is my file structure:
server.ts
routes
user.ts
view
index.ejs
/user
index.ejs
On my server.js this code works as expected:
router
.get("/", (context: any) => {
context.render("view/index.ejs");
});
But, in my routes/user.ts, the following code does NOT work:
router
.get("user/", (ctx: any) => {
ctx.render("../view/user/index.ejs")
});
Inside render, I tried:
${Deno.cwd}"/../view/student/index.ejs"
"/../view/user/index.ejs"
and out of desperation:
"/view/user/index.ejs"
I'm sure there's a super easy, most obvious thing I'm missing here.
Here is workaround,
import { Application, send, Router } from "https://deno.land/x/oak/mod.ts";
import { viewEngine, engineFactory, adapterFactory, ViewConfig } from 'https://deno.land/x/view_engine/mod.ts';
const ejsEngine = engineFactory.getEjsEngine();
const oakAdapter = adapterFactory.getOakAdapter();
const app = new Application();
app.use(viewEngine(oakAdapter, ejsEngine, {
viewRoot: "./view",
viewExt: ".ejs",
}));
const router = new Router();
app.use(router.routes());
app.use(router.allowedMethods());
router
.get('/', async (ctx, next) => {
ctx.render("index", { data: { name: "Nikhil" } });
});
await app.listen({ port: 8000 });
Inside the view folder i have index.ejs
Run files as,
deno run --allow-net --allow-read server.ts
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>EJS HOLA</h1>
Hobbies of <%=data.name%>
</body>
</html>
For more resource to add, you can look at view_engine

Directly Hitting static css file url( http://localhost:3000/css/style.css ) response is working but not applied on ejs template elements?

Hye guys I am newbie in node.js .
I am working with ejs partial template . I have been stuck for days in this issue where i have public/css/style.css file in root directory .
where i am accessing this file from views/contact.ejs and views/home.ejs
Contact.ejs
!-- begin snippet: js hide: false console: true babel: false -->
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="/public/css/style.css" type=β€œtext/cssβ€œ>
</head>
<body>
<%- include('partialComponents/naviagations.ejs') %>
<H3>CONTACTS US !</H3>
<h2>LEARN THE BEST CODE TECHNIQUES HERE ....</h2>
<h2>EJS FILE TEMPLATE </h2>
</body>
</html>
main.js
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
//app.set('views', '/views'); // settings the path to view folder to express can locate
//by default express will check the view folder in first root to the js file
app.use(express.static('public'))
app.get('/profile/:id', (req, res) => {
var data = {
age: 23,
job: 'software developer',
hobbies: ['eating', 'fishing', 'gaming']
}
console.log('hey');
res.render('profile', { name: req.params.id, data: data });
});
app.get('/home', (req, res) => {
res.render('home');
});
app.get('/', (req, res) => {
res.render('home');
});
app.get('/contact', (req, res) => {
res.render('contact');
});
app.listen(3000);
// console.log(__dirname + "");
style.css
body {
background-color: skyblue;
text-align: center;
}
h3 {
font-size: 50px;
font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
color: white;
}
h2 {
color: white;
}
.testid {
color: red;
}
here is my file structure
πŸ‘¨β€πŸ« You're missing in the <link href=""> because you have set public as your static folder, your style is in the location:http://localhost:3000/css/style.css. That is why when you call /public/css/style.css it cannot be found, because it will look for thepublic folder inside the public folder and you do not have it other than thecss folder there..
So, You can change your <link href=""/> with this code below πŸ‘‡:
<link rel="stylesheet" href="/css/style.css" href="text/css">
For an example: You can see on my codesandbox
Sandbox code: https://codesandbox.io/s/quirky-borg-ghwc0
For view only: https://ghwc0.sse.codesandbox.io/contact
I hope it can help you πŸ™.

Resources