I'm all new to Angular, and im currently trying to build a frontend, while learning to use Angular.
I have build a test-app where i am implementing authentication using an API i have writting.
The authentication works fine, however i an strugling wrapping my head around how to implement a specific functionallity.
Almost all of the app is locked behind authentication.
The idea is:
If a user visits any page in the app, while not logged in, the app should redirect the user to the login-page.
All of this works great.
However the login-page needs a totally different layout. No design elements from the "main design" is used on the login page. Even the css class on the body tag is different.
What would be the best way to solve this?
I have tried to do some *ngif in the app.component.html file, however that didnt work as expected.
Im also totally stomped on how to change the body-class in index.html.
I hope this makes any sense.
Im posting some sourcecode below. If more is needed let me know.
app.component.html:
<ng-container *ngIf="accountService.currentUser$ | async">
<app-preloader></app-preloader>
<app-nav></app-nav>
<app-sidebar></app-sidebar>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0">Dashboard</h1>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</div>
<!-- /.content-header -->
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<router-outlet></router-outlet>
</div><!-- /.container-fluid -->
</section>
<!-- /.content -->
</div>
<app-footer></app-footer>
</ng-container>
<ng-container *ngIf="(accountService.currentUser$ | async) === null">
<router-outlet></router-outlet>
</ng-container>
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Client</title>
<base href="/">
<!-- Google Font: Source Sans Pro -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<app-root></app-root>
</body>
</html>
app.routing.module.ts:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { MainComponent } from './main/main.component';
import { LoginComponent } from './login/login.component';
import { UserComponent } from './user/user.component';
import { AuthGuard } from './_guards/auth.guard';
const routes: Routes = [
{
path: '',
runGuardsAndResolvers: 'always',
canActivate: [AuthGuard],
children: [
{path: '', component: MainComponent},
{path: 'user', component: UserComponent}
]
},
{path: 'login', component: LoginComponent},
{path: '**', component: MainComponent, pathMatch: 'full', canActivate: [AuthGuard]},
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
For this you can create Layout module and create your Inside and Outside layout component and add <router-outlet></router-outlet> in both components and then in your app-routing.module.ts file create route like this
{
path: '',
component: OutsideLayoutComponent,
canActivate: [ExternalAuthGuard],
children: [
{ path: '', loadChildren: './modules/auth/auth.module#AuthModule' },
]
},
{
path: '',
component: InsideLayoutComponent,
canActivate: [AuthGuard],
children: [
{ path: 'ticket', loadChildren: './modules/ticket-retrieval/ticket-retrieval.module#TicketRetrievalModule' }
{ path: 'error', component: GenericErrorPageComponent },
{ path: 'invalid-session', component: InvalidSessionPageComponent },
{ path: 'un-authorized', component: UnAuthorizedComponent }
]
},
You need to create AuthGuard, and authguard will handle user is login or not based on that redirect user to specific page. And base on routes layout will be set.
NOTE: You must have basic understanding of Angular LazyLoding
Related
Laravel 9
Using vite
Vue 3, Vue-router
Run command vite build and turn off vite server, all links in browser url get '/build/'
In code
<router-link to="/index">Index</router-link>
<router-link to="/">Main</router-link>
<router-view></router-view>
In browser
Vite config
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '#vitejs/plugin-vue'
export default defineConfig({
plugins: [
vue(),
laravel({
input: ['resources/css/app.css', 'resources/js/app.js'],
refresh: true,
}),
],
});
Blade
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<!-- Fonts -->
<link href="https://fonts.bunny.net/css2?family=Nunito:wght#400;600;700&display=swap" rel="stylesheet">
#vite(['resources/css/app.css', 'resources/js/app.js'])
<!-- Styles -->
<style>
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent}[hidden]{display:none}html{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}*,:after,:before{box-sizing:border-box;border:0 solid #e2e8f0}a{color:inherit;text-decoration:inherit}svg,video{display:block;vertical-align:middle}video{max-width:100%;height:auto}.bg-white{--bg-opacity:1;background-color:#fff;background-color:rgba(255,255,255,var(--bg-opacity))}.bg-gray-100{--bg-opacity:1;background-color:#f7fafc;background-color:rgba(247,250,252,var(--bg-opacity))}.border-gray-200{--border-opacity:1;border-color:#edf2f7;border-color:rgba(237,242,247,var(--border-opacity))}.border-t{border-top-width:1px}.flex{display:flex}.grid{display:grid}.hidden{display:none}.items-center{align-items:center}.justify-center{justify-content:center}.font-semibold{font-weight:600}.h-5{height:1.25rem}.h-8{height:2rem}.h-16{height:4rem}.text-sm{font-size:.875rem}.text-lg{font-size:1.125rem}.leading-7{line-height:1.75rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-1{margin-left:.25rem}.mt-2{margin-top:.5rem}.mr-2{margin-right:.5rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.ml-4{margin-left:1rem}.mt-8{margin-top:2rem}.ml-12{margin-left:3rem}.-mt-px{margin-top:-1px}.max-w-6xl{max-width:72rem}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.p-6{padding:1.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.pt-8{padding-top:2rem}.fixed{position:fixed}.relative{position:relative}.top-0{top:0}.right-0{right:0}.shadow{box-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px 0 rgba(0,0,0,.06)}.text-center{text-align:center}.text-gray-200{--text-opacity:1;color:#edf2f7;color:rgba(237,242,247,var(--text-opacity))}.text-gray-300{--text-opacity:1;color:#e2e8f0;color:rgba(226,232,240,var(--text-opacity))}.text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.text-gray-500{--text-opacity:1;color:#a0aec0;color:rgba(160,174,192,var(--text-opacity))}.text-gray-600{--text-opacity:1;color:#718096;color:rgba(113,128,150,var(--text-opacity))}.text-gray-700{--text-opacity:1;color:#4a5568;color:rgba(74,85,104,var(--text-opacity))}.text-gray-900{--text-opacity:1;color:#1a202c;color:rgba(26,32,44,var(--text-opacity))}.underline{text-decoration:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.w-5{width:1.25rem}.w-8{width:2rem}.w-auto{width:auto}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}#media (min-width:640px){.sm\:rounded-lg{border-radius:.5rem}.sm\:block{display:block}.sm\:items-center{align-items:center}.sm\:justify-start{justify-content:flex-start}.sm\:justify-between{justify-content:space-between}.sm\:h-20{height:5rem}.sm\:ml-0{margin-left:0}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:pt-0{padding-top:0}.sm\:text-left{text-align:left}.sm\:text-right{text-align:right}}#media (min-width:768px){.md\:border-t-0{border-top-width:0}.md\:border-l{border-left-width:1px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}#media (min-width:1024px){.lg\:px-8{padding-left:2rem;padding-right:2rem}}#media (prefers-color-scheme:dark){.dark\:bg-gray-800{--bg-opacity:1;background-color:#2d3748;background-color:rgba(45,55,72,var(--bg-opacity))}.dark\:bg-gray-900{--bg-opacity:1;background-color:#1a202c;background-color:rgba(26,32,44,var(--bg-opacity))}.dark\:border-gray-700{--border-opacity:1;border-color:#4a5568;border-color:rgba(74,85,104,var(--border-opacity))}.dark\:text-white{--text-opacity:1;color:#fff;color:rgba(255,255,255,var(--text-opacity))}.dark\:text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.dark\:text-gray-500{--tw-text-opacity:1;color:#6b7280;color:rgba(107,114,128,var(--tw-text-opacity))}}
</style>
<style>
body {
font-family: 'Nunito', sans-serif;
}
</style>
</head>
<body>
<div id="app">
</div>
</body>
</html>
app.js
import './bootstrap';
import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount("#app")
So i want to get in browser like this
http://localhost:8000/
http://localhost:8000/index
Without "build"
When i user working server vite with php artisan serve, all work fine, but when i want to prepare data for deploing, so do vite build, and turn off vite server, so append this work in url, but i dont want this word there.
For me working when i remove import.meta.env.BASE_URL from
Befor
const router = createRouter({
history: createWebHistory(**import.meta.env.BASE_URL**),
routes
});
After
const router = createRouter({
history: createWebHistory(),
routes
});
Please remove import.meta.env.BASE_URL parameter from createWebHistory() function in /resources/js/router/index.js.
Like this.
const router = createRouter({
history: createWebHistory(),
routes
});
I cannot figure out why my css file is not working. I added my css, html and settings.py files. Can anyone help? I've tried collectstatic but get an error:
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'D:\\mysite\\dreamboard\\static\\dreamboard\\style.css'
I tried replacing my path in the STATICFILES_DIRS but it still does not work. I'm not sure what to do. It could be the bootstrap? Or something. I want to have a style sheet so I can my form to a popup button. Everything is titled and spelled correctly. Any ideas?
Here are my files:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% load crispy_forms_tags %}
<link rel="stylesheet" type="text/css" href="{% static 'dreamboard/style.css' %}">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/73cead4581.js" crossorigin="anonymous"></script>
<title>Hello, world!</title>
</head>
<body class="bg-light">
<h1>Hello, world!</h1>
<div class="container">
<div class="row bg-dark">
<div class=" col-sm">
<h1 style="color:white">Dreamboard</h1>
</div>
<div class="col-sm">
<button class="btn-lg btn-primary" type="submit">Add Dream</button>
</div>
</div>
</div>
</div>
<form class="" action="" method="post" autocomplete="off">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
{{form.first_name|as_crispy_field}}
</div>
<div class="col-md-6">
{{form.last_name|as_crispy_field}}
</div>
</div>
{{form.dreamItem|as_crispy_field}}
<br>
<button type="submit" class="d-grid gap-2 col-12 btn btn-success">Submit</button>
</form>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.5.4/dist/umd/popper.min.js" integrity="sha384-q2kxQ16AaE6UbzuKqyBE9/u/KzioAlnx2maXQHiDX9d4/zp8Ok3f+M7DPm+Ib6IU" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-pQQkAEnwaBkjpqZ8RU1fF1AKtTcHJwFl3pblpTlHXybJjHpMYo79HY3hIi4NKxyj" crossorigin="anonymous"></script>
-->
</body>
</html>
css
.body {
background-color: blue;
}
.title {
color: blue;
}
settings.py
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'wpx1d9%a4(9-c%+$=or6ez+9*d7&)lo!d5(8cu3##3votm)!72'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'dreamboard',
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'dreams',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
"/mysite/dreamboard/static/dreamboard/style.css",
]
I am not sure because I don't think many people use an absolute path to connect to static files. Try creating a new folder named "static", In the same folder where you have the manage.py file. and add this into your settings.py.
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_DIR = os.path.join(BASE_DIR,"static")
check the settings.py code here
Add the below code directing django to the static file location
# Static files (CSS, JavaScript, Images) #https://docs.djangoproject.com/en/3.1/howto/static-files/
> STATIC_URL = '/static/'
> STATICFILES_DIRS = [
> STATIC_DIR,
> ]
Now link it in the HTML using ,
<link rel="stylesheet" href="{% static 'css/base.css' %}">
(create a folder called css inside the static folder in your base directory)
You have named your class "bg-light", but in your css code it looks like you are trying to target a class in your css file named "body" when you don't have a class name body. If you are tying to access the body tag which it looks like your trying to do then you have to get rid of the "." you have in your ".body{}". You have also done the same thing for your title tag which is ".title". Your not targeting what you think your trying to target.
#Your HTML Code
<body class="bg-light">
#Your css code >>> pay close attention to the "."
.body {
background-color: blue;
}
Try This:
body{
background-color: blue;
}
title{
background-color:blue;
}
I'm working on a visual studio 2017 template project of .net core 2 + Angular SPA template.
I'm having a problem that some of html elements appear twice, 1 appearance with css applied and the other isn't.
when i deploy the app it looks like in the image below.
As you can see the place holder 'Choose a number' and the dropdown arrow appear twice.
When i press the upper arrow 2 dropdowns are opened with the options.
If i press the downer arrow only the downer dropdown opened.
the whole div should be coloured in blue but only the "not in place" elements are blue.
the component is a prime-NG component but it occurs with other NPM packages (kendo UI for example).
I assume that it might be related to the order of css files and NPM loading during bootstrap but I can't find the place
index.cshtml:
#{
ViewData["Title"] = "Home Page";
}
<app>Loading...</app>
<script src="~/dist/vendor.js" asp-append-version="true"></script>
#section scripts {
<script src="~/dist/main-client.js" asp-append-version="true"></script>
}
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - GSM.WebMonitorTool</title>
<base href="~/" />
<link rel="stylesheet" href="~/dist/vendor.css" asp-append-version="true" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">
</head>
<body>
#RenderBody()
#RenderSection("scripts", required: false)
</body>
</html>
choose-number.component.html:
<div class="query-context-all">
<div class="dropdown">
<p-dropdown [options]="numbers" [(ngModel)]="chosenNumber" placeholder="Choose a number"></p-dropdown>
</div>
</div>
choose-number.component.ts :
import { Component } from '#angular/core';
import { SelectItem } from 'primeng/api';
#Component({
selector: 'context-input',
templateUrl: './context-input.component.html',
styleUrls: ['./context-input.component.css']
})
export class ContextInputComponent {
chosenNumber: string;
numbers: SelectItem[];
constructor() {
this.numbers = [
{ label: "1", value: "1" },
{ label: "2", value: "2" },
{ label: "3", value: "3" }];
}
}
So thanks to John Velasquez, I understood that i had to add primeNG's css file to webpack. Actually each shared components or fonts npm may require this addition. As a beginner with Angular i didn't know they must be added explicitly so I add here my steps that solved it, hoping it will save some time for others :)
steps:
adding the css file to webpack.config.vendor.vs - add the line 'primeng/resources/primeng.css' to nonTreeShakableModules array
update the rules of shared config, a few lines down, to { test: /\.(png|woff|woff2|eot|ttf|svg|jpe?g|gif)(\?|$)/, use: 'url-loader?limit=100000' }
run webpack --config webpack.config.vendor.js
from cmd/powershell, when path is the project folder.
I followed the series codetube "youtube clone" and I did everything like the Alex but the Vue component not working. I am not working on localhost but on server. I would be very glad for any suggestions.
My app.js
require('./bootstrap');
Vue.component('videoup', require('./components/VideoUpload.vue'));
const app = new Vue({
el: '#app'
});
My VideoUpload.vue file:
<template>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Upload</div>
<div class="panel-body">
...
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component mounted.')
}
}
</script>
My blade file:
#extends('layouts.app')
#section('content')
<videoup></videoup>
#endsection
My app.blade file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Styles -->
<!-- <link href="/css/app.css" rel="stylesheet">-->
<link rel="stylesheet" href="/css/app.css">
<!-- Scripts -->
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
</head>
<body>
<div id="app">
#include('layouts.partials._navigation')
#yield('content')
</div>
<script src="/js/app.js"></script>
</body>
</html>
My gulfpile.js:
const elixir = require('laravel-elixir');
require('laravel-elixir-vue-2');
require('laravel-elixir-webpack-official');
elixir((mix) => {
mix.sass('app.scss')
.webpack('app.js');
});
My webpack.config.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
// vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js'
}
},
devServer: {
historyApiFallback: true,
noInfo: true
},
devtool: '#eval-source-map'
};
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map',
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
};
It's difficult to debug your setup because I have no idea what tutorial you followed, how you are bundling your code (webpack or browserify) or what build tools you are using (gulp, elixir etc), but I think the most important thing is to understand how Vue works, and then you will be able to better understand how to solve this yourself.
Firstly, vue has two builds - a standalone build and a runtime-only build. The difference between these is that the standalone build includes a template compiler and the runtime-only build does not.
Render Functions
Vue compiles templates in to render functions to work (which are just javascript functions), it doesn't use HTML at all, so if you haven't written a render function or you haven't pre-compiled your components (using .vue files and a bundler like browserify or webpack) then you must use the standalone build; and this includes the base component itself, so the important thing to know is:
If you are trying to use a component inside anything other than a .vue file you need to use the standalone build.
because you need the compiler to turn the HTML into a render function.
So, looking at your code, you are trying to use your component inside a .blade.php file, which isn't a single file component so you will need the standalone build in your project.
When using npm, vue imports the runtime-only build by default:
// ES6
import `Vue` from `vue` // this imports the runtime-only build
// ES5
var Vue = require('vue'); // this requires the runtime-only build
But you need to make sure you are using the standalone build, and how you do this depends on whether you use webpack or browserify. If you are using webpack, you need to add the following to your webpack config:
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js'
}
}
If you are using browserify you will need to add the following to your package.json:
"browser": {
"vue": "vue/dist/vue.common"
},
And also make sure that resources/assets/views/layouts/app.blade.php wraps everything in a div with the id app:
...
<body>
<div id="app">
...
</div>
</body>
...
Update
Based on your webpack config it looks like your issue is here:
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
This says you are compiling main.js in the src folder and outputting it to the dist folder as build.js.
Laravel uses a different structure, so you will need to change this to:
entry: './resources/assets/js/app.js',
output: {
path: path.resolve(__dirname, './public/js'),
publicPath: '/public/',
filename: 'app.js'
},
This now says, compile resources/assets/js/app.js and output the file to public/js/app.js. I don't use webpack myself so that may need a little tweaking, but that should get your project up and running.
I had the same issue. the following solved it for me..
I changed:
require('./components/mycomponent.vue')
to:
import MyComponent from "./components/mycomponent.vue";
I try to Sending Push Notification with Ionic.io.
so I do than this demo: https://devdactic.com/android-push-notifications/
But when I Run in android, I have this error:
app.js:27 Uncaught TypeError: Ionic.User.anonymousId is not a function
this is my index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic-platform-web-client/dist/ionic.io.bundle.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<!-- Cordova is bootstrapped by ionic-platform-web-client, uncomment this if you remove ionic-platform-web-client... -->
<!-- <script src="cordova.js"></script> -->
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter">
<!--
The nav bar that will be updated as we navigate between views.
-->
<ion-nav-bar class="bar-stable">
<ion-nav-back-button>
</ion-nav-back-button>
</ion-nav-bar>
<!--
The views will be rendered in the <ion-nav-view> directive below
Templates are in the /templates folder (but you could also
have templates inline in this html file if you'd like).
-->
<ion-nav-view></ion-nav-view>
</body>
</html>
And my app.js:
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'ionic.service.core', 'starter.controllers', 'starter.services', 'ionic.service.push'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function () {
var io = Ionic.io();
var push = new Ionic.Push({
"onNotification": function (notification) {
alert('Received push notification!');
},
"pluginConfig": {
"android": {
"iconColor": "#0000FF"
}
}
});
var user = Ionic.User.current();
if (!user.id) {
user.id = Ionic.User.anonymousId();
}
// Just add some dummy data..
user.set('name', 'Simon');
user.set('bio', 'This is my little bio');
user.save();
var callback = function (data) {
push.addTokenToUser(user);
user.save();
};
push.register(callback);
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
// Each tab has its own nav history stack:
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl'
}
}
})
.state('tab.chats', {
url: '/chats',
views: {
'tab-chats': {
templateUrl: 'templates/tab-chats.html',
controller: 'ChatsCtrl'
}
}
})
.state('tab.chat-detail', {
url: '/chats/:chatId',
views: {
'tab-chats': {
templateUrl: 'templates/chat-detail.html',
controller: 'ChatDetailCtrl'
}
}
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/dash');
});
I have only follow this instruction:
ionic start devdactic-android-push cd devdactic-android-push ionic add
ionic-platform-web-client ionic plugin add phonegap-plugin-push
--variable SENDER_ID=your-gcm-project-number ionic io init
ionic push --google-api-key your-google-api-key ionic config set
gcm_key your-gcm-project-number ionic config set dev_push false
Can you help me?
You might just want to start with trying the limited push setup, Ionic provides their own guide for it which is really easy to follor:
http://docs.ionic.io/docs/push-limited-setup
If you got that figured out, you can send a notification to your app and the app will open an alert message with the notification content. Then you can start using native pushes, which requires allmost the same code:
http://docs.ionic.io/docs/push-full-setup
And here is a guide on how to send pushes using the ionic.io framework:
http://docs.ionic.io/docs/push-sending-push