I have a main app page component with a search bar. The Search results that come back is in cards And I am looking to set up a "Click here to view more detail" that would be placed in each card. And it would link to the Details page of the one result clicked. How do I link these components on Vue and if the id could be passed? I am hoping that upon click of the button the component renders on the same page and not a new tab.
Once I click on "click here" It updates the link to http://localhost:8081/#/{name:'Details',%20params:%20{id:%20result._gddid}}
and
I get an [Vue warn]: Property or method "results" is not defined on the instance but referenced during render.
Thank you!
app.vue
<template>
<div id="app">
<Header/>
<SearchForm v-on:search="search"/>
<SearchResults
v-if="results.length > 0"
v-bind:results="results"
v-bind:reformattedSearchString="reformattedSearchString"/>
<Details
v-bind:results="results"
/>
<Pagination
v-if="results.length > 0"
v-bind:prevPageToken="api.prevPageToken"
v-bind:next_page="api.scrollId"
v-on:prev-page="prevPage"
v-on:next-page="nextPage"
/>
</div>
</template>
<script>
import Header from './components/layout/Header';
import SearchForm from './components/SearchForm';
import SearchResults from './components/SearchResults';
import Details from './components/Details'
import Pagination from './components/Pagination';
import axios from 'axios';
export default {
name: 'app',
components: {
Header,
SearchForm,
SearchResults,
Details,
Pagination
},
data() {
return {
results: [],
reformattedSearchString: '',
api: {
baseUrl: 'https://test.org/api/v1/articles?',
max: 25,
q: '',
prevPageToken: '',
scrollId: ''
}
};
},
methods: {
search(searchParams) {
this.reformattedSearchString = searchParams.join(' ');
this.api.q = searchParams.join('+');
const { baseUrl, q, max} = this.api;
const apiUrl = `${baseUrl}&term=${q}&title_like=${q}&recent&max=${max}&full_results`;
this.getData(apiUrl);
},
prevPage() {
const { baseUrl, q, max, prevPageToken } = this.api;
const apiUrl = `${baseUrl}&term=${q}&title_like=${q}&max=${max}&pageToken=${prevPageToken}`;
this.getData(apiUrl);
},
nextPage() {
const { baseUrl, q, max,scrollId } = this.api;
const apiUrl = `${baseUrl}&term=${q}&title_like=${q}&max=${max}&recent&full_results&scroll_id=${scrollId}`;
this.getData(apiUrl);
},
getData(apiUrl) {
axios
.get(apiUrl)
.then(res => {
this.results = res.data.success.data;
this.api.prevPageToken = res.data.success.data.prevPageToken;
this.api.next_page = res.data.scrollId;
})
.catch(error => console.log(error))
}
}
};
</script>
SearchResults.vue
<template>
<div class="container mb-3">
<div class="d-flex mb-3">
<div class="mr-auto">
<h3>Search Results for "{{ reformattedSearchString }}"</h3>
</div>
<div class="btn-group ml-auto" role="group">
<button
#click="changeDisplayMode('grid')"
type="button"
class="btn btn-outline-secondary"
v-bind:class="{ active: displayMode === 'grid' }"
>
<i class="fas fa-th"></i>
</button>
<button
#click="changeDisplayMode('list')"
type="button"
class="btn btn-outline-secondary"
v-bind:class="{ active: displayMode === 'list' }"
>
<i class="fas fa-list"></i>
</button>
</div>
</div>
<div class="card-columns" v-if="displayMode === 'grid'">
<div class="card" v-bind:key="result._gddid" v-for="result in results">
<ArticleGridItem v-bind:result="result"/>
</div>
</div>
<div v-else>
<div class="card mb-2" v-bind:key="result._gddid" v-for="result in results">
<ArticleListItem v-bind:result="result"/>
</div>
</div>
<div class="card mb-2" v-bind:key="result._gddid" v-for="result in results">
<Details v-bind:result="result"/>
</div>
</div>
</template>
<script>
import ArticleListItem from './ArticleListItem';
import ArticleGridItem from './ArticleGridItem';
import Details from './Details';
export default {
name: 'SearchResults',
components: {
ArticleListItem,
ArticleGridItem,
Details,
},
data() {
return {
title: 'Search Results',
displayMode: 'grid'
};
},
methods: {
changeDisplayMode(displayMode) {
this.displayMode = displayMode;
}
},
props: ['results', 'reformattedSearchString']
};
</script>
<style scoped>
button:focus {
box-shadow: none !important;
}
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';
import moment from 'moment'
Vue.config.productionTip = false
Vue.filter('formatDate', function (value) {
if (!value) return ''
return moment(value.toString()).format('MM/DD/YYYY hh:mm')
})
Vue.use(VueRouter)
import Details from './components/Details';
const router = new VueRouter({
routes: [
{
path: '/Details/:id',
name: 'Details',
component: Details
}
]
})
new Vue({
router,
render: h => h(App),
}).$mount('#app')
ArticleListItem.vue
<template>
<div>
<div class="card-body">
<h6 class="card-text">{{ result.title }}</h6>
<p class="card-subtitle mb-2 text-muted"
>{{ result.publisher }} | {{ result.journal }} | {{ result.year }}</p>
<a :href="'https://test.org/api/articles?docid=' + result._gddid" target="_blank">
<i class="fa fa-download" alt="Download"> </i>
</a>
<router-link dark to="{name:'Details', params: {id: result._gddid}}">
Click here for more Details
</router-link>
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name: 'ArticleListItem',
props: ['result'],
}
</script>
Details.vue
<template>
<div class="Details">
<div class="container">
<div class="row">
<div class="col-md-12" v-for="result in results" :key="result._gddid">
<div v-if="id == result._gddid">
<h1>{{result.title}}</h1>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'Details',
props: ['result'],
};
</script>
Once I click on "click here" It updates the link to http://localhost:8081/#/{name:'Details',%20params:%20{id:%20result._gddid}}
Glancing over the code it appears that within ArticleListItem.vue the router-link's to attr isn't bound so it's treated as a string.
Currently: to="{name:'Details', params: {id: result._gddid}}"
Try: :to="{name:'Details', params: {id: result._gddid}}" so it's passed as an object.
I get an [Vue warn]: Property or method "results" is not defined on the instance but referenced during render.
Within Details.vue you have props: ['result'], but in the v-for it looks for results which isn't defined within data() nor within props.
As for the # appearing, vue-router's default mode is hash, if you're not wanting to use # you can set it to history via:
const router = new VueRouter({
mode: 'history',
routes: [...]
})
But beware you'll need a server running to handle the routing; You can find more info at https://router.vuejs.org/guide/essentials/history-mode.html#html5-history-mode
Related
I am trying to make cards from an array of objects containing ids and URL (relative paths ) to my images. But when I try to use mapping to return arrays and use background CSS property to set images I am unable to do it. Below is the code
import React from "react";
import { useState } from "react";
import { Fragment } from "react";
// import { Link } from "react-router-dom";
import styles from "../Styles/Services.module.scss";
const Services = () => {
const [pic, setPic] = useState(1);
const list = [
{ id: 1, url: "../Images/mentorship.jpg" },
{ id: 2, url: "../Images/entertainment.jpg" },
{ id: 3, url: "../Images/support.jpg" },
{ id: 4, url: "../Images/opportunity.jpg" },
{ id: 5, url: "../Images/counselling.jpg" },
];
// const clickHandler = (e) => {
// console.log(e.target.value);
// setPic(e.target.value);
// };
return (
<Fragment>
<section
className="bg-light p-5 text-dark"
style={{ fontFamily: "Lato" }}
>
<div className="container py-5 ">
<div className="display-2 text-center">Our Services</div>
<div className={`${styles.bodyCard}`}>
<div className={`${styles.options}`}>
{list.map((x) => {
var a = x.url;
return (
<div
key={x.id}
value={x.id}
className={`${styles.option} ${
pic === x.id ? styles.active : ""
}`}
onClick={() => setPic(x.id)}
style={{
background: `url(${
require(a).default
})`,
backgroundSize: "auto 100%",
backgroundPosition: "center",
}}
>
<div className={`${styles.shadow}`}></div>
<div className={`${styles.label}`}>
<div className={`${styles.icon}`}>
<i className="fas fa-walking"></i>
</div>
<div className={`${styles.info}`}>
<div className={`${styles.main}`}>Blonkisoaz</div>
<div className={`${styles.sub}`}>
Omuke trughte a otufta
</div>
</div>
</div>
</div>
);
})}
;
</div>
</div>
</div>
</section>
</Fragment>
);
};
export default Services;
I am unable to display images at code background
background: `url(${require(x.url).default})
But When I use this it works.
background: `url(${require("../Images/mentorship.jpg").default})
It gives this error in React
enter image description here
**Kindly do not make it a duplicate as I have checked other similar questions as well and have found no answer there. Thanks **
import React from "react";
import { useState } from "react";
import { Fragment } from "react";
// import { Link } from "react-router-dom";
import styles from "../Styles/Services.module.scss";
import image1 from "../Images/mentorship.jpg";
import image2 from "../Images/entertainment.jpg";
const Services = () => {
const [pic, setPic] = useState(1);
const list = [
{ id: 1, url: image1 },
{ id: 2, url: image2 },
];
// const clickHandler = (e) => {
// console.log(e.target.value);
// setPic(e.target.value);
// };
return (
<Fragment>
<section
className="bg-light p-5 text-dark"
style={{ fontFamily: "Lato" }}
>
<div className="container py-5 ">
<div className="display-2 text-center">Our Services</div>
<div className={`${styles.bodyCard}`}>
<div className={`${styles.options}`}>
{list.map((x) => {
var a = x.url;
return (
<div
key={x.id}
value={x.id}
className={`${styles.option} ${
pic === x.id ? styles.active : ""
}`}
onClick={() => setPic(x.id)}
style={{
background: `url(${a})`,
backgroundSize: "auto 100%",
backgroundPosition: "center",
}}
>
<div className={`${styles.shadow}`}></div>
<div className={`${styles.label}`}>
<div className={`${styles.icon}`}>
<i className="fas fa-walking"></i>
</div>
<div className={`${styles.info}`}>
<div className={`${styles.main}`}>Blonkisoaz</div>
<div className={`${styles.sub}`}>
Omuke trughte a otufta
</div>
</div>
</div>
</div>
);
})}
;
</div>
</div>
</div>
</section>
</Fragment>
);
};
export default Services;
As mentioned in the answerer above by https://stackoverflow.com/users/12902108/samira , it will work, just set style as style={{ background: `url(${photo})` }} assuming image is imported as photo .
I have few li tags whose data comes from loop. There is also a link 'images', When you click it, it should open respective modal like For 'Cat' row cat image should come,For 'Architecture' row Architecture image should come,For 'baboon' row baboon image should come. For now only cat link is coming on click of 'image' link.you can use these link for particular image
Architecture - https://homepages.cae.wisc.edu/~ece533/images/arctichare.png
Baboon - https://homepages.cae.wisc.edu/~ece533/images/baboon.png , Here is the code below with demo url
https://stackblitz.com/edit/angular-327axj?file=src%2Fapp%2Fapp.component.ts
app.component.html
<hello name="{{ name }}"></hello>
<div>
<pre>
</pre>
<ul>
<li *ngFor="let item of statusdata" (click)="toggleActive(item, !item.active)">
<span>{{item.id}}</span>
<span>{{item.name}}</span>
<button class="btn btn-lg btn-outline-primary" (click)="open(content)">Image</button>
</li>
</ul>
</div>
<ng-template #content let-modal>
<div class="modal-header">
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<img style="width:100%" src="https://homepages.cae.wisc.edu/~ece533/images/cat.png" />
</div>
</ng-template>
<hr>
app.component.ts
import { Component } from '#angular/core';
import {NgbModal, ModalDismissReasons} from '#ng-bootstrap/ng-bootstrap';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
statusdata: any;
closeResult: string;
constructor(private modalService: NgbModal) {}
ngOnInit() {
this.statusdata = [
{ id: 1, name: "Cat"},
{ id: 2, name: "Architecture"},
{ id: 3, name: "baboon" },
];
this.statusdata.forEach(item => {
this.getCacheItemStatus(item);
});
}
toggleActive(item, activeStatus = true) {
item.active = activeStatus;
localStorage.setItem(`item:${item.id}`, JSON.stringify(item));
}
getCacheItemStatus(item) {
const cachedItem = localStorage.getItem(`item:${item.id}`);
if (cachedItem) {
const parse = JSON.parse(cachedItem); // Parse cached version
item.active = parse.active; // If the cached storage item is active
}
}
open(content) {
this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
}
Right now, you're hard coding the image url in the modal to use the cat image as follows:
<img style="width:100%" src="https://homepages.cae.wisc.edu/~ece533/images/cat.png" />
which causes the same image to be displayed in all modals.
You could maintain a variable for the image name and set it to the required image when you open the modal.
While calling the open method, pass the item name which will act as the image source:
<button class="btn btn-lg btn-outline-primary" (click)="open(content, item.name)">Image</button>
and handle it in the typescript class:
open(content, source) {
this.imageSource = source;
...
where imageSource is just a variable:
imageSource: any;
And now the updated image URL will be:
<img style="width:100%" src="https://homepages.cae.wisc.edu/~ece533/images/{{imageSource}}.png" />
Here is the updated stackblitz:
https://stackblitz.com/edit/angular-bslf3q
My project contains 4 components: Course-List, Course-Detail, Course-Play, Course Quiz, and the scheme is like that:
The data is pass like that: every course have array of segment and every segments have array of questions. All the data I get from a backend server (Ruby on Rails API project) and it pass correctly.
This is the interfaces of each data structure:
export interface ICourse {
id: number;
title: string;
autor: string;
segments: ISegment[];
}
export interface ISegment {
id: number;
unit_id: number;
unit_title: string;
name: string;
type: string;
data: string;
questions: IQuestion[];
}
export interface IQuestion {
id: number;
question: string;
answer1: string;
answer2: string;
answer3: string;
answer4: string;
correct: number;
}
I'm having a problem with course-quiz component.
This is how the quiz looks:
Problems:
When click submit and next the data's not saving
I want to add option of coloring the correct answer and user answer after press submit
I want that when all questions are answered that new page show instead (not working probably because the first)
This is the project in stackblitz. The project not working because stackblitz isn't working with sass. I'll add relevant code also here:
app-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { CourseListComponent } from './courses/course-list/course-list.component';
import { CourseDetailComponent } from './courses/course-detail/course-detail.component';
import { CoursePlayComponent } from './courses/course-play/course-play.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { CourseQuizComponent } from './courses/course-play/course-quiz/course-quiz.component';
// Routing array - set routes to each html page
const appRoutes: Routes = [
{ path: '', redirectTo: '/courses', pathMatch: 'full', runGuardsAndResolvers: 'always' },
{ path: 'courses', component: CourseListComponent, pathMatch: 'full', runGuardsAndResolvers: 'always' },
{ path: 'courses/:id', component: CourseDetailComponent, pathMatch: 'full', runGuardsAndResolvers: 'always' },
{ path: 'courses/:id/segments/:id', component: CoursePlayComponent, pathMatch: 'full', runGuardsAndResolvers: 'always',
children: [{ path: 'questions/:id', component: CourseQuizComponent }]
},
{ path: '**', component: PageNotFoundComponent, pathMatch: 'full', runGuardsAndResolvers: 'always' }];
#NgModule({
imports: [RouterModule.forRoot(appRoutes, { onSameUrlNavigation: 'reload' })],
exports: [RouterModule]
})
export class AppRoutingModule { }
course-play.component.ts
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute, Router, Routes, NavigationEnd } from '#angular/router';
import { MatSidenavModule } from '#angular/material/sidenav';
import { LocalStorage } from '#ngx-pwa/local-storage';
import { DomSanitizer } from '#angular/platform-browser';
import { ICourse } from '../course';
import { ISegment } from '../course';
import { CourseService } from '../course.service';
// Couse-play decorator
#Component({
selector: 'lg-course-play-course-play',
templateUrl: './course-play.component.html',
styleUrls: ['./course-play.component.sass']
})
export class CoursePlayComponent implements OnInit {
errorMessage: string;
course: ICourse;
courseId: number;
public currentSegment: ISegment;
public showChildren: boolean = false;
constructor(private courseService: CourseService,
private route: ActivatedRoute,
private router: Router,
public sanitizer: DomSanitizer) { }
ngOnInit() {
// save this course id from course-detail and get http request from the service
this.courseId = JSON.parse(localStorage.getItem("courseId"))
this.getCourse(this.courseId);
}
// Get course detail by id
getCourse(id: number) {
this.courseService.getCourse(this.courseId).subscribe(
course => {
this.course = course;
// get the current segment id to use it on the html file
const id = +this.route.snapshot.paramMap.get('id');
this.getCurrentSegment(id);
},
error => this.errorMessage = <any>error);
}
// search in course single segment by id and save it in currentSegment
// to use it in the html file
getCurrentSegment(id: number){
this.currentSegment = this.course.segments.find(d => d.id === id);
}
changeShowChildren() {
this.showChildren = !this.showChildren;
}
}
course-play.component.html
<div class="row content" *ngIf="course">
<!-- Side nav-bar -->
<div class="col-md-3">
<!-- Image Logo -->
<div id="head_sidebar">
<img src="./assets/images/lg-white.png" class="d-inline-block align-top logo" alt="" routerLink="/courses" style="outline: none">
<h3>{{course.title}}</h3>
</div>
<div class="col-md-12 sidenav">
<!-- Menu elemets -->
<div class="nav nav-pills nav-stacked" *ngFor="let unit of course.segments | groupBy: 'unit_title'; let i = index">
<h6 class="course_play_title">Unit {{ i+1 }}: {{ unit.key }} </h6>
<ul>
<li class="course_play_item" *ngFor="let lesson of unit.value">
<a class="nav-link" [routerLink]="['/courses', course.id, 'segments', lesson.id]" (click)=getCurrentSegment(lesson.id)>{{lesson.name}}</a>
</li>
</ul>
</div>
</div>
</div>
<!-- Body -->
<div class="col-md-9 no-gutters" *ngIf="currentSegment">
<!-- Video Div -->
<div class="col-md-12 course_play_body text-center" *ngIf="currentSegment.segment_type === 'Video'">
<h1>{{currentSegment.name}}</h1>
<p class="small-text" *ngIf="course.segments?.length > 0">lesson {{currentSegment.id}} of {{course.segments?.length}}</p>
<hr>
<iframe frameborder="0" allowfullscreen="true" [src]='currentSegment.data | safe'></iframe>
<button type="button" class="prev btn btn-primary btn-lg" *ngIf="currentSegment.id > 1" [routerLink]="['/courses', course.id, 'segments', currentSegment.id-1]" (click)=getCurrentSegment(currentSegment.id-1)>Previous</button>
<button type="button" class="next btn btn-primary btn-lg" *ngIf="currentSegment.id < course.segments?.length" [routerLink]="['/courses', course.id, 'segments', currentSegment.id+1]" (click)=getCurrentSegment(currentSegment.id+1)>Next</button>
</div>
<!-- Quiz Div -->
<div class="col-md-12 course_play_body" *ngIf="currentSegment.segment_type === 'Quiz'">
<div class="col-md-12 course_play_body text-center" *ngIf="showChildren === false">
<h1>{{currentSegment.name}}</h1>
<p class="text-left"> Now that you've finished this unit, It's time to take a short quiz and see what you learned so far!
You'll need to choose one out of four answers which you think is correct.
After you've finished the quiz, you'll get your grade. feel free to re-take this quiz as much as you like.
Good Luck!
</p>
<p class="text-left big-text"> {{currentSegment.questions.length}} questions </p>
<a (click) = "showChildren = true"><h4>Start Quiz</h4></a>
<button style="margin-top: 30%" type="button" class="prev btn btn-primary btn-lg" *ngIf="currentSegment.id > 1" [routerLink]="['/courses', course.id, 'segments', currentSegment.id-1]" (click)=getCurrentSegment(currentSegment.id-1)>Previous</button>
<button style="margin-top: 30%" type="button" class="next btn btn-primary btn-lg" *ngIf="currentSegment.id < course.segments?.length" [routerLink]="['/courses', course.id, 'segments', currentSegment.id+1]" (click)=getCurrentSegment(currentSegment.id+1)>Next</button>
</div>
<quiz-course *ngIf="showChildren === true" [items]="currentSegment?.questions"></quiz-course>
</div>
</div>
course-quiz.component.ts
import { Component, OnInit, Input } from '#angular/core';
import { ActivatedRoute, Router, Routes, NavigationEnd } from '#angular/router';
import { ICourse } from '../../course';
import { ISegment } from '../../course';
import { IQuestion } from '../../course';
import { CourseService } from '../../course.service';
import { PagerService } from '../../pager.service';
import * as _ from 'underscore';
#Component({
selector: 'quiz-course',
templateUrl: './course-quiz.component.html',
styleUrls: ['./course-quiz.component.sass']
})
export class CourseQuizComponent implements OnInit {
// the data I get from course-play component
#Input() items: IQuestion[];
// variables for pagination
pagedItems: IQuestion[];
pager: any = {};
public userAnswers = ['0', '0', '0', '0']; // array of user answers
public index: int; // index of userAnswers
public checkedAnswer: int; // the checked answer the user choose
public correctAnswer: boolean = false; // true if his answer correct, else false
public sum: int; // sum of the questions answered. needed to check if user finished quiz
constructor(private courseService: CourseService,
private route: ActivatedRoute,
private router: Router,
private pagerService: PagerService) { }
ngOnInit() {
this.setPage(1);
this.checkedAnswer = 0;
this.index = 0;
this.sum = 0;
}
// change pages
setPage(page: number) {
if (page < 1 || page > this.pager.totalPages) {
return;
}
// get pager object from service
this.pager = this.pagerService.getPager(this.items.length, page);
// get current page of items
this.pagedItems = this.items.slice(this.pager.startIndex, this.pager.endIndex + 1);
}
isChecked(value){
this.checkedAnswer = value;
}
// get value of the checked answer, check if it's correct and save it to the answer array
submitAnswer(correct) {
// if the user answer all the questions, go to finished page
if (sum == this.items.length) {
}
if (this.checkedAnswer == 0) {
// do something to notify user that an answer need to be checked
}
else if (this.checkedAnswer == correct) {
this.correctAnswer = true;
this.userAnswers[this.index] = "correct";
}
else {
this.correctAnswer = false;
this.userAnswers[this.index] = "incorrect";
}
this.index = this.index + 1;
this.sum = this.sum + 1;
}
}
course-quiz.component.html
<div class="container" *ngIf="sum < 4">
<div class="text-left quiz-body" *ngFor="let item of pagedItems">
<form>
<!-- items being paged -->
<h3>Question {{item.id}}/{{items.length}}</h3>
<h6>Question {{item.question}}</h6>
<ul class="items">
<li><input type="radio" id="answer1" name="answer" value="1" (click)="isChecked(1)"><label for="answer1">1. {{item.answer1}}</label></li>
<li><input type="radio" id="answer1" name="answer" value="2" (click)="isChecked(2)"><label for="answer2">2. {{item.answer2}}</label></li>
<li><input type="radio" id="answer1" name="answer" value="3" (click)="isChecked(3)"><label for="answer3">3. {{item.answer3}}</label></li>
<li><input type="radio" id="answer1" name="answer" value="4" (click)="isChecked(4)"><label for="answer4">4. {{item.answer4}}</label></li>
</ul>
<button type="submit" class="btn btn-primary mb-2" (click)="submitAnswer(item.correct)">Submit</button>
<!-- Submit Buttom -->
<!-- pager -->
<ul *ngIf="pager.pages && pager.pages.length" class="pagination">
<li class="page-item" [ngClass]="{disabled:pager.currentPage === 1}">
<a class="page-link" (click)="setPage(1)">First</a>
</li>
<li class="page-item" [ngClass]="{disabled:pager.currentPage === 1}">
<a class="page-link" (click)="setPage(pager.currentPage - 1)">Previous</a>
</li>
<li class="page-item" *ngFor="let page of pager.pages" [ngClass]="{active:pager.currentPage === page}">
<a class="page-link" (click)="setPage(page)">{{page}}</a>
</li>
<li class="page-item" [ngClass]="{disabled:pager.currentPage === pager.totalPages}">
<a class="page-link" (click)="setPage(pager.currentPage + 1)">Next</a>
</li>
<li class="page-item" [ngClass]="{disabled:pager.currentPage === pager.totalPages}">
<a class="page-link" (click)="setPage(pager.totalPages)">Last</a>
</li>
</ul>
</form>
</div>
</div>
<!-- If the user finished the quiz, this div will displaying instead -->
<div class="container" *ngIf="sum == 4">
<h3> You have just finished the quiz! </h3>
</div>
I am trying to show result from json to table with vue.js
i have no result this is the script:
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h4 class="title">Progress Queue's details Live</h4>
</div>
<div class="card-content table-responsive table-full-width">
<el-table :data="tableData2">
<el-table-column label="Name" property="name"></el-table-column>
<el-table-column class="danger" label="Numbers" property="numbers"></el-table-column>
</el-table>
</div>
</div>
</div>
<script>
import ChartCard from 'src/components/UIComponents/Cards/ChartCard.vue'
Vue.use(Table)
Vue.use(TableColumn)
const WorldMap = () => ({
component: import('./../Maps/WorldMap.vue'),
loading: Loading,
delay: 200
})
import axios from 'axios';
import Vue from 'vue'
import {Table, TableColumn} from 'element-ui'
Vue.use(Table)
Vue.use(TableColumn)
// Vue.use(tableRowClassName)
import vSelect from 'vue-select';
//Vue.component('v-select', VueSelect.VueSelect)
export default {
components: {
vSelect,
StatsCard
},
data () {
return {
tableData2: [],
},
mounted() {
axios.get("/statcard").then(response => {
this.tableData2.push({
name: response.data.queue,
numbers: reponse.data.queue_count
});
});
}
}
i recieve no data
the result of the json is :
{"queue_count":"4","queue":"OP_AD_WIN_HARDWARE"},{"queue_count":"35","queue":"OPBO_WIN_Fiber_pend_i"},{"queue_count":"5","queue":"OP_AD_WIN_RELOCATION"},{"queue_count":"44","queue":"OPBO_WIN_Act_pend_i"}]}
Remove mounted from data.
Don't add plugins multiple times.
The element documentation says, that prop is correct, not property.
Work on your line indentation.
<template>
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h4 class="title">Progress Queue's details Live</h4>
</div>
<div class="card-content table-responsive table-full-width">
<el-table :data="tableData2">
<el-table-column label="Name" prop="queue_count"></el-table-column>
<el-table-column class="danger" label="Numbers" prop="queue"></el-table-column>
</el-table>
</div>
</div>
</div>
</template>
<script>
import Vue from 'vue';
import vSelect from 'vue-select';
import axios from 'axios';
import { Table, TableColumn } from 'element-ui';
import ChartCard from 'src/components/UIComponents/Cards/ChartCard.vue';
Vue.use(Table);
Vue.use(TableColumn);
const WorldMap = () => ({
component: import('./../Maps/WorldMap.vue'),
loading: Loading,
delay: 200
});
export default {
components: {
vSelect,
StatsCard
},
data() {
return {
tableData2: []
};
},
mounted() {
axios.get('/statcard').then(response => {
this.tableData2 = response.data.queue_progress;
});
}
};
</script>
I am testing a web app of firebase login with angular Dart in Chrome browser at localhost, but while clicking on the sign-in the popup for login gets disappeared within 1 sec and doesn't result with successful login. While testing it on Chromium it's working.
Can anyone tell what should I do to fix this?
firebase_service.dart
import 'dart:async';
import 'package:angular/angular.dart';
import 'package:firebase/firebase.dart' as fb;
#Injectable()
class FirebaseService {
fb.User user;
fb.Auth _fbAuth;
fb.GoogleAuthProvider _fbGoogleAuthProvider;
FirebaseService() {
fb.initializeApp(
apiKey: "AIzaSyBOShlCgUeqTL99n32bjWdNlkH1RPk9Xx4",
authDomain: "my-app.firebaseapp.com",
databaseURL: "https://my-app.firebaseio.com",
storageBucket: "my-app.appspot.com",
);
_fbGoogleAuthProvider = new fb.GoogleAuthProvider();
_fbAuth = fb.auth();
_fbAuth.onAuthStateChanged.listen(_authChanged);
}
void _authChanged(fb.User event) {
user = event;
}
Future signIn() async {
try {
await _fbAuth.signInWithPopup(_fbGoogleAuthProvider);
}
catch (error) {
print("$runtimeType::login() -- $error");
}
}
void signOut() {
_fbAuth.signOut();
}
}
app_component.html
<header class="material-header shadow">
<div class="material-header-row">
<material-button icon
class="material-drawer-button" (trigger)="drawer.toggle()">
<material-icon icon="menu"></material-icon>
</material-button>
<span class="material-header-title">{{appTitle}}</span>
<div class="material-spacer"></div>
<nav class="material-navigation">
<material-button class="material-drawer-button" icon
materialTooltip="Notifications"
(trigger)="">
<material-icon icon="notifications"></material-icon>
</material-button>
<div id="popup-sign-out" class="popup-user" *ngIf="fbService.user != null">
<material-button class="material-drawer-button" icon
popupSource
#source="popupSource"
materialTooltip="More options"
(trigger)="basicPopupVisible = !basicPopupVisible">
<material-icon icon="more_vert"></material-icon>
</material-button>
<material-popup defaultPopupSizeProvider
enforceSpaceConstraints
[source]="source"
[(visible)]="basicPopupVisible">
<div header class="custom-header">
<img id="popup-user-image" [src]="fbService.user?.photoURL">
<div class="user-detail">
<div id="user-name">{{fbService.user?.displayName}}</div>
<div id="email">{{fbService.user?.email}}</div>
</div>
</div>
<div group class="custom-popup-body">
<material-list class="popup-list" size="3">
<div group>
<material-list-item class="sign-out-button"
*ngIf="fbService.user != null"
(trigger)="fbService.signOut()">
<material-icon icon="exit_to_app" [style.color]="iconColor"
class="material-list-item-primary" aria-hidden="true">
</material-icon>
Sign out
</material-list-item>
</div>
</material-list>
</div>
</material-popup>
</div>
</nav>
<nav class="material-navigation">
<div id="sign-in" class="user" *ngIf="fbService.user == null">
<material-button raised class="sign-in-button" (trigger)="fbService.signIn()">
<img class="google-icon" src="g-logo.png"/>
Sign In
</material-button>
</div>
<div id="sign-out" class="user" *ngIf="fbService.user != null">
<img id="header-user-image" [src]="fbService.user?.photoURL">
</div>
</nav>
</div>
</header>
app_component.dart
import 'package:angular/angular.dart';
import 'package:angular_components/angular_components.dart';
import 'package:yns_app/services/firebase_service.dart';
#Component(
selector: 'my-app',
styleUrls: const [
'app_component.css',
'package:angular_components/src/components/app_layout/layout.scss.css',
],
templateUrl: 'app_component.html',
directives: const [
materialDirectives,
DeferredContentDirective,
MaterialButtonComponent,
MaterialIconComponent,
MaterialPersistentDrawerDirective,
MaterialToggleComponent,
MaterialListComponent,
MaterialListItemComponent,
ClickableTooltipTargetDirective,
DarkThemeDirective,
MaterialIconTooltipComponent,
MaterialInkTooltipComponent,
MaterialPaperTooltipComponent,
MaterialPopupComponent,
MaterialTooltipDirective,
MaterialTooltipTargetDirective,
MaterialTooltipSourceDirective,
NgIf,
Search,
NameGenerator,
],
providers: const [
materialProviders,
popupBindings,
DefaultPopupSizeProvider,
],
)
class AppComponent {
final FirebaseService fbService;
bool basicPopupVisible = false;
bool end = false;
String get tooltipMsg => 'All the best messages appear in tooltips.';
String get longString => 'Learn more about web development with AngularDart '
'here. You will find tutorials to get you started.';
AppComponent(FirebaseService this.fbService);
}
#Injectable()
PopupSizeProvider createPopupSizeProvider() {
return const PercentagePopupSizeProvider();
}
#Directive(selector: '[defaultPopupSizeProvider]', providers: const [
const Provider(PopupSizeProvider, useFactory: createPopupSizeProvider)
])
class DefaultPopupSizeProvider {}
connect the domain or the sub-domain to the hosted project, under the Hosting section.