I'm trying to use the vue2-editor with my project but I can't get it to work. It says: "Failed to mount component: template or render function not defined." When I try to use import instead of require I get the error message: "Couldn't find a declaration file for module...". I've set up a types.d.ts to solve this but still doesn't work.
Any help is appreciated!
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import PopupImages from "./PopupImages.vue";
import VModal from 'vue-js-modal';
import UploadFile from "./UploadFile.vue";
import axios from 'axios';
import router from "../router";
import store from "../store";
const VueEditor = require('vue2-editor').default;
class Route {
name: string;
description: string;
constructor(){
this.name = "";
this.description = "";
console.log(VueEditor);
}
}
Vue.use(VModal, { dynamic: true });
#Component({
components: {
VModal,
UploadFile,
VueEditor
}
})
export default class NewRoute extends Vue {
route: Route;
content: any;
constructor(){
super();
this.route = new Route();
this.content = '<h1> Testing </h1>';
}
sendData(){
let newRoute = {
name : this.route.name,
description : this.route.description
}
console.log(newRoute);
axios.get('')
.then((response) => {
console.log(response);
})
.catch((error: any) => {
console.log(error);
})
}
}
</script>
<template>
<div id="newRoute">
<vue-editor v-model="content"></vue-editor>
<modal name="addRoute" :width="400" :height="450">
<form>
<h1>Insert new trail</h1>
<p>
<label for ="route">Route name</label>
<input type = "text" id="route" name ="route" v-model="route.name" size = "30" maxlength ="30" required/>
</p>
<p>
<label for = "description">Description</label>
<textarea id= "description" name = "description" v-model="route.description">
</textarea>
</p>
<p>Upload JSON or GPX file</p>
<UploadFile></UploadFile>
<br/>
<button type="submit" #click ="sendData">Submit</button>
</form>
</modal>
</div>
</template>
Related
I am currently refactoring some old code. I want to get the data of of a vue form in order to post into my database through laravel's api. Looking at the json output I get & the controllers method everythings looks fine to me. I also tried to move the Route::post code to the regular web.php without success.
I'll post a screenshot of my schema & exact errors message (xhr cancelled).
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('/session', 'SessionController#index');
Route::get('/session/{id}', 'SessionController#currentRoom');
Route::post('/create', 'SessionController#create');
Route::put('/session/{id}', 'SessionController#update');
Route::delete('/session/{id}', 'SessionController#destroy');
SessionController.php
<?php
namespace App\Http\Controllers;
use App\Services\LongPolling;
use Faker\Generator;
use App\Session;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Response;
class SessionController extends Controller
{
public function create(Request $request)
{
// $session = new Session();
// $session->playerName = $faker->name;
// $session->playerId = $faker->numberBetween($min = 0, $max = 127);
// $session->roomName = $faker->name;
// $session->roomDescription = $faker->text;
// $session->overallValue = $faker->numberBetween($min = 10, $max = 70);
// $session->playerValue = $faker->randomDigitNotNull;
// $session->isAdmin = $faker->boolean ? false : true;
// $session->save();
$validator = Validator::make($request->all(), [
'roomName' => 'required|string',
'roomDescription' => 'required|string'
]);
if ($validator->fails()){
return Response::json(['errors' =>$validator->errors()], 422);
}
$session = Session::create([
'roomName' => $request('roomName'),
'roomDescription' => $request('roomDescription')
]);
return Response::json(['session' => $session,
'message' => 'success'], 200);
}
Create.vue
<template>
<div>
<form>
<strong>roomname:</strong>
<br />
<input type="text" v-model="roomName" />
<br />
<strong>description:</strong>
<br />
<input type="text" v-model="roomDescription" />
<br />
<button v-on:click="formSubmit">Click me</button>
</form>
</div>
</template>
<script>
export default {
components: {},
data() {
return {
roomName: "",
roomDescription: ""
};
},
methods: {
formSubmit() {
axios
.post("/api/create", {
roomName: this.roomName,
roomDescription: this.roomDescription
})
.then(function(response) {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
}
};
</script>
<style>
</style>
room.blade.php
<!-- Stored in resources/views/child.blade.php -->
#extends('layouts.app')
#section('title', 'Scrumpoker')
#section('content')
<br>
<br>
<create>
</create>
#endsection
app.js
require('./bootstrap');
import Vue from 'vue'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
Vue.use(Vuetify)
const opts = {}
// Vue.component('App', require('./components/App.vue').default);
// Vue.component('Card', require('./components/card.vue').default);
// Vue.component('session', require('./components/Session.vue').default);
Vue.component('create', require('./components/Create.vue').default);
const app = new Vue({
el: '#app',
vuetify: new Vuetify(),
});
Check if it's related to CORS and not related to POST?
I created a class named alert, and I use it to display alerts whenever new post is created or deleted or changed.
but there is one issue, when I put the setAlert inside a DELETE/POST/PUT function, if the latter is located inside a service component, it gives me an error saying: ERROR
but when I move the function into its component.ts file, it works properly without any issues. So why is that happening and what can I do to make it work in a service?
Here is my Alert.ts:
export class alert{
"status" : boolean;
"text": string;
constructor(){
this.status=false;
this.text="";
}
public setAlert(text){
this.status = true;
this.text = text;
}
public close(){
this.status = false;
}
}
Here is my html file:
<div class="forms container">
<form #postForm="ngForm">
<div class="form-group">
<label for="title">Title</label>
<input [(ngModel)]="formService.form.title"
name="title"
id="title"
type="text"
class="form-control"
>
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea [(ngModel)]="formService.form.body"
name= "body"
id="body"
cols="30"
rows="10"
class="form-control"
></textarea>
</div>
<button class="btn btn-success" (click) = "formService.editForm()">Save</button>
<button class="btn btn-danger pull-right" (click) = "formService.deleteForm()">Delete</button>
<div class="container mt-4">
<div class="row">
<div class="col">
<div *ngIf = "alert.status" class="alert alert-success
alert-dismissible fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"
(click) = "alert.close()">
<span aria-hidden="true">×</span>
</button>
{{alert.text}}
</div>
</div>
</div>
</div>
</form>
</div>
Here is component.ts file:
import { Component, OnInit, OnDestroy } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { FormService } from './forms.service';
import { HttpClient } from '#angular/common/http';
import { alert } from './alert';
#Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.css']
})
export class FormsComponent implements OnInit {
alert: alert;
id: any;
posts: any;
constructor(public formService: FormService ,private route: ActivatedRoute,
private router: Router, private http: HttpClient) { }
ngOnInit() {
this.id=this.route.snapshot.params['id'];
this.alert = new alert();
this.posts = this.formService.getForms(this.id).subscribe(
(forms: any) => {
this.formService.form = forms[0];
}
);
}
}
And here is service.ts file:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { form } from './form-interface';
import { alert } from './alert';
#Injectable({
providedIn: 'root'
})
export class FormService {
formsUrl = "https://jsonplaceholder.typicode.com/posts";
form: form = {
id: 0,
userId: 0,
title: '',
body: ''
};
alert: alert;
constructor(private http: HttpClient) { }
ngOnInit() {
this.alert = new alert();
}
getForms(id) {
return this.http.get('https://jsonplaceholder.typicode.com/posts'
+ "?id=" + id)
}
editForm() {
fetch(this.formsUrl + "/" + this.form.id, {
method: 'PUT',
body: JSON.stringify(this.form),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
this.alert.setAlert("Post has been successfully saved !");
}
deleteForm() {
this.http.delete(this.formsUrl + "/" + this.form.id)
.subscribe(
data => {
console.log("DELETE Request is successful ", data);
this.alert.setAlert("Post has been successfully deleted !");
},
error => {
console.log("Error", error);
}
);
}
}
Services don't have ngOnInit life cycle, change your code from ngOnInit to constructor.
constructor(private http: HttpClient) {
this.alert = new alert();
}
Only components and directives have life cycle hooks:
A Component has a lifecycle managed by Angular itself. Angular creates it, >renders it, creates and renders its children, checks it when its data-bound >properties change and destroy it before removing it from the DOM.
Directive and component instances have a lifecycle as Angular creates, updates, >and destroys them.
I'm using vue.js for the first time and I'm having an issue I've researched but not gotten to the bottom of yet. For advice so far, I've found these articles:
https://laracasts.com/discuss/channels/vue/vuex-anybody-typeerror-thisstorecommit-is-not-a-function?page=1
Uncaught TypeError: this.$store.commit is not a function
https://forum.vuejs.org/t/vuex-this-store-commit-is-not-a-function/31001
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=7&cad=rja&uact=8&ved=0ahUKEwjk_I-AhejbAhWPv1MKHRjMAyEQFghtMAY&url=https%3A%2F%2Falligator.io%2Fvuejs%2Fintro-to-vuex%2F&usg=AOvVaw2Pimf2n5yvOU5NpRsaCfCz
I have this store:
import Vue from 'vue';
import Vuex from 'vuex';
const state = {
loggedIn: false
}
const mutations = {
truthify: state => state.loggedIn = true
}
const getters = {
loggedIn: state = state.loggedIn
}
const store = new Vuex.Store {
state,
getters,
mutations,
actions
}
export default store;
Pointing to this component:
<template>
<div class="login">
<div id="loginMain">
<form>
<label for="username">Username:</label>
<input type="text" id="username"></input>
<label for="password">Password:</label>
<input type="text" id="password"></input>
{{ loggedIn }}
<input type="button" value="submit" id="post-form" #click="testLogin"/>
</form>
</div>
</div>
</template>
<script>
import { mapState, vuex } from 'vuex'
import store from '#/store/'
export default {
name: 'Login',
data: function() {
return {
loggedIn: ''
}
},
computed: {
returnMessage: function() {
return this.$store.state.loggedIn
}
},
methods: {
testLogin(){
console.log('foo');
this.$store.commit('truthify');
}
},
store: store,
}
</script>
I'm not sure what the issue is.
Okay so I have been facing the dreadful:
TypeError: Cannot read property 'Id' of undefined
Before we get started:
#angular/cli: 1.4.4
node: 6.10.3
npm: 3.10.10
Just to give more context, I am trying to perform one way data binding to edit a component by taking the Id from its component class and flow in a single direction to display the view template. That's all.
Below is the following that will hopefully try reproduce the problem and in turn figure out a solution.
SQL Table Definition:
CREATE TABLE [ExampleTable]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Col2] [nvarchar](50) NULL,
[Col3] [int] NULL,
[Col4] [int] NULL
)
ExampleTable.ts
export interface ExampleTable {
Id;
Col2;
Col3;
Col4;
}
export class CreateExampleTableModel {
SomeForeignKey?: number;
Col2: string;
Col2: number;
Col2: number;
}
export class EditExampleTable {
}
empty-tables.component.ts
import {
Component
} from '#angular/core';
import {
Router
} from "#angular/router";
import {
EmptyTableServiceService
} from "../../services/empty-table.service";
import {
EmptyTable
} from "../../models/outModels/EmptyTable";
#Component({
selector: 'app-empty-tables',
templateUrl: './empty-tables.component.html',
styleUrls: ['./empty-tables.component.css']
})
export class EmptyTablesComponent {
//Table data
emptyTable: EmptyTable[];
constructor(
private router: Router,
private emptyTableServiceService: EmptyTableServiceService) {
}
edit(emptyTable: EmptyTable) {
this.router.navigate(['emptyTables/edit', emptyTable.Id]);
}
}
EmptyTableService:
import {
Injectable
} from '#angular/core';
import {
Http
} from '#angular/http';
import 'rxjs/add/operator/toPromise';
import {
EmptyTable,
CreateExampleTableModel
} from "../models/outModels/EmptyTable";
#Injectable()
export class EmptyTableService {
constructor(private http: Http, ) {}
getEmptyTable(Id: string): Promise<EmptyTable> {
return this.http.get(`${this.auth.apiUrl}/api/emptyTables/get/${Id}`, { headers: this.auth.header })
.toPromise()
.then(response => response.json() as EmptyTable)
.catch(error => this.logging.handleError(error));
}
update(emptyTable: EmptyTable): Promise < EmptyTable > {
return this.http.post(`${this.auth.apiUrl}/api/emptyTables/update`, JSON.stringify(emptyTable), {
headers: this.auth.header
})
.toPromise()
.then(response => response.json() as EmptyTable)
.catch(error => this.logging.handleError(error));
}
}
EmptyTableEditComponent:
import {
Component,
OnInit
} from '#angular/core';
import {
ActivatedRoute,
ParamMap,
Router
} from '#angular/router';
import {
EmptyTableService
} from "../../../services/empty-table.service";
import {
EmptyTable
} from "../../../models/outModels/EmptyTable";
export class EmptyTableEditComponent implements OnInit {
model: EmptyTable;
constructor(
private route: ActivatedRoute,
private router: Router,
private emptyTableService: EmptyTableService
) {}
ngOnInit() {
this.loading = true;
this.route.paramMap
.switchMap((params: ParamMap) => this.emptyTableService.getEmptyTable(params.get('Id')))
.subscribe(emptyTable => {
this.model = emptyTable;
});
}
goBack(): void {
this.router.navigate(['/emptyTables']);
}
save(): void {
this.loading = true;
this.emptyTableService.update(this.model).then(
emptyTable => {
this.model = emptyTable;
},
error => {
console.log(error);
}
);
}
}
My suspicion is that in my getEmptyTable(Id: string) which returns a Promise of EmptyTables is that I am passing in my Id parameter as a string value whereas in my table definition from my DB it is an integer however according to my understanding, url parameters are always in string format. I tried the following:
i. Setting my Id to a number data type and I call the toString() on the Idparameter in the apiUrl like so:
getEmptyTable(Id: number): Promise<EmptyTable> {
return this.http.get(`${this.auth.apiUrl}/api/emptyTables/get/${Id.toString()}`, { headers: this.auth.header })
.toPromise()
.then(response => response.json() as EmptyTable)
.catch(error => this.logging.handleError(error));
}
But this does not make much of a difference. Lastly, please find the view template which I render:
<div class="container">
<p-messages [(value)]="messages"></p-messages>
<p-panel *ngIf="model">
<p-header>
Edit EmptyTable {{model.Name}}
</p-header>
<form name="form" (ngSubmit)="save()">
<div class="form-group">
<label>Col 2</label>
<input type="text" class="form-control" name="col2" [(ngModel)]="model.Col2" required />
</div>
<div class="form-group">
<label>Col 3</label>
<input type="text" class="form-control" name="col3" [(ngModel)]="model.Col3" required />
</div>
<div class="form-group">
<button pButton type="button" class="ui-button-secondary" (click)="goBack()" label="Back" icon="fa-chevron-left"></button>
<button pButton class="ui-button-success pull-right" label="Save" icon="fa-save"></button>
<app-loader *ngIf="loading"></app-loader>
</div>
</form>
</p-panel>
</div>
To wrap this up, it complains in the following function:
edit(emptyTable: EmptyTable) {
this.router.navigate(['emptyTables/edit', emptyTable.Id]);
}
Note: Please don't run the snippets as there is no output to them. This was the quickest way to format my code. Manual indentation was not cutting it.
The problem was found below:
<ng-template let-user="rowData" pTemplate="body">
<button type="button" pButton (click)="edit(distributor)" icon="fa-edit"></button>
</ng-template>
let-user should have been changed to let-distributor and all works.
I'm new to Angular2 and spent a lot of time trying to fix a simple thing.
As you can see, I only want to access the Local Storage (bottom function, ui())and send the contents to the View, Register.components.html. I tried various blog but I failed every-time.
So I can't really post an error, but how do I just access the local storage and display the contents to my view? Also ui() isn't being called. How do I call it?
Register.component.ts
import { Component, OnInit } from '#angular/core';
import {ValidateService} from '../../services/validate.service';
import {AlarmService} from '../../services/alarm.service';
import {FlashMessagesService} from 'angular2-flash-messages';
import {Router} from '#angular/router';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
hours: String;
id: String;
constructor(
private validateService: ValidateService,
private FlashMessage: FlashMessagesService,
private Router: Router,
private AlarmService: AlarmService
){
}
ngOnInit() {
}
onRegisterSubmit(){
var user = {
hours: (new Date(this.hours.replace('T', ' ').replace('-', '/'))).valueOf(),
id: new Date().getTime(),
flag: 0
}
setTimeout(() => {
this.FlashMessage.show('Your alarm has been added.', {cssClass: 'alert-success', timeout: 5000});
}, 10);
var storage = localStorage.getItem('users');
var final = [];
if (storage == null || typeof(storage) == undefined )
{ final.push(user);
localStorage.setItem('users', JSON.stringify(final));
let time = new Date().getTime()
this.AlarmService.setUpAlarms(time);
}else{
var get = JSON.parse(localStorage.getItem('users'));
var size = Object.keys(get).length;
for(var i =0; i< get.length; i++){
final.push(get[i]);
}
final.push(user);
localStorage.setItem('users', JSON.stringify(final));
let time = new Date().getTime()
this.AlarmService.setUpAlarms(time);
}
}
ui(){
var storage = localStorage.getItem('users');
if (storage == null || typeof(storage) == undefined ){
var HERO = localStorage.getItem('users');
}
console.log(HERO);
const HEROES = HERO
}
}
This is my HTML view
<form (submit)="onRegisterSubmit()">
<div class = "container">
<div class="overlay">
<div id="alarm-dialog">
HEKK
<h2>Set alarm at</h2>
<div class="form-group">
<label class="hours">
<input type="datetime-local" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" class="form-control" [(ngModel)]="hours" name="hours" value="0" min="0" required/>
</label>
</div>
<a class="close"></a>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Set Alarm">
</div>
</form>
<tr *ngFor="let hero of heroes">
<td>{{hero.hours}}</td>
</tr>
If you want ui() called when the component loads, you can do it in ngOnInit:
ngOnInit() {
this.ui();
}
Also, declare heroes as a property on your component so it can be bound to the view:
export class RegisterComponent implements OnInit {
heroes: any[]; // Maybe add a type instead of "any"
// etc
}
And fix up your ui method a bit:
ui() {
this.heroes = JSON.parse(localStorage.getItem('users'));
}