I am trying to find the distance between a location input from the user and a fixed location. I want to use the DistanceMatrix service from google platform, but I keep getting the "google is not defined" error.
import { Component } from '#angular/core';
import { Router } from '#angular/router';
import { AlertController, ToastController } from '#ionic/angular';
import { DataService } from '../data.service';
declare var google : any;
#Component({
selector: 'app-checkout',
templateUrl: './checkout.page.html',
styleUrls: ['./checkout.page.scss'],
})
export class CheckoutPage {
payment = ""
name : string = ""
phone : string = ""
address : string = ""
constructor(private alertController : AlertController, private router:Router, private dataService : DataService, private toastController : ToastController) {
var to = new google.maps.places.Autocomplete(document.getElementById("address") as HTMLInputElement)
}
I would also like for the input to autocomplete as the user types.
I have been stuck on this for 3 days now.
Any help will be greatly appreciated.
I will answer this with a little delay, but one way to fix it is as follows:
First you need to install #types/googlemaps :
npm install --save #types/googlemaps
Then if you are using Angular-cli, add googlemaps to types in src/tsconfig.app.json:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": [
"googlemaps"
]
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
After that, you probably won't have this problem anymore.
source: https://roufid.com/angular-uncaught-referenceerror-google-not-defined/
Related
I'm new to learning Angular and what seems like a simple solution for importing an external array is causing an error I just don't understand. I've used AngularJS and didn't have any of these issues. Below is the error I'm receiving
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:4200/assets/models.json", ok: false, …}
error
:
{error: SyntaxError: Unexpected token l in JSON at position 10 at JSON.parse (<anonymous>) at XMLHtt…, text: "[↵ {↵ label: "Metal Man",↵ sample: "/assets…es",↵ textures: "6",↵ materials: "1"↵ }↵]↵"}
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
:
"Http failure during parsing for http://localhost:4200/assets/models.json"
name
:
"HttpErrorResponse"
ok
:
false
status
:
200
statusText
:
"OK"
url
:
"http://localhost:4200/assets/models.json"
__proto__
:
HttpResponseBase
In my ts file I have the following request being made from the assets folder-
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { CommonModule } from '#angular/common';
import { DomSanitizer } from '#angular/platform-browser';
#Component({
selector: 'app-work',
templateUrl: './work.component.html',
styleUrls: ['./work.component.css']
})
export class WorkComponent implements OnInit {
viewMode = 'work';
modelwork: any;
constructor( private http: HttpClient, public sanitizer: DomSanitizer ) {
this.sanitizer = sanitizer;
}
ngOnInit(): void {
this.http.get<any>('./assets/models.json').subscribe(
data => {
this.modelwork = data;
})
$(document).ready(function() {
$(".tag").hide();
$(".grid-item").hover(function() {
$(this).children(".tag").stop(true, true).slideToggle(500);
return false;
})
});
}
}
I would very much like to understand what causes this issue, how it can be resolved, and if there is any good documentation on this would be great. I'm using a book called ngBook for my learning platform along with a video series from Lynda. Both seem to lack a lot of information on error issues. I've tried Git, but what I'm looking at as solutions do not quite make sense to me. I'm hoping to learn from this mistake and would appreciate any guidance the community has to offer. Thank you to all who respond in advance!
From the error it looks like your model.json is not valid JSON. Try putting double quotes around all of your keys.
[
{
"label": "Metal Man",
"sample": "/assets…es",
"textures": "6",
"materials": "1"
}
]
I am pretty new to Angular 2. I am trying to achieve the same task as Highlight the search text - angular 2 what is mentioned in above post.
I have created the pipe filter my question is where should i keep the pipe filter and where should i place the inner html div.
Copying the problem:
A messenger displays the search results based on the input given by the user. Need to highlight the word that is been searched, while displaying the result. These are the html and component that is been used.
component.html
<div *ngFor = "let result of resultArray">
<div>Id : result.id </div>
<div>Summary : result.summary </div>
<div> Link : result.link </div>
</div>
Component.ts
resultArray : any = [{"id":"1","summary":"These are the results for the searched text","link":"http://www.example.com"}]
This resultArray is fetched from hitting the backend service by sending the search text as input. Based on the search text, the result is fetched. Need to highlight the searched text, similar to google search.
How should i apply the search filter and where should i keep the inner html?
There are some tweaks to be made to the regex replacement regarding case, but here's a starting point:
//our root app component
import {Component, NgModule, VERSION, Pipe, PipeTransform} from '#angular/core'
import {BrowserModule, DomSanitizer} from '#angular/platform-browser'
#Pipe({
name: 'highlight'
})
export class HighlightSearch implements PipeTransform {
constructor(private sanitizer: DomSanitizer){}
transform(value: any, args: any): any {
if (!args) {
return value;
}
// Match in a case insensitive maneer
const re = new RegExp(args, 'gi');
const match = value.match(re);
// If there's no match, just return the original value.
if (!match) {
return value;
}
const result = value.replace(re, "<mark>" + match[0] + "</mark>");
return this.sanitizer.bypassSecurityTrustHtml(result);
}
}
#Component({
selector: 'my-app',
template: `
<input (input)="updateSearch($event)">
<div *ngFor="let result of resultArray" [innerHTML]="result.summary | highlight: searchTerm"></div>
`,
})
export class App {
results: string[]
searchTerm: string;
constructor() {
this.resultArray = [
{
"id": "1",
"summary": "These are the results for the searched text",
"link": "http://www.example.com"
},
{
"id": "2",
"summary": "Here are some more results you searched for",
"link": "http://www.example.com"
}
]
}
updateSearch(e) {
this.searchTerm = e.target.value
}
}
#NgModule({
imports: [ BrowserModule ],
declarations: [ App, HighlightSearch ],
bootstrap: [ App ]
})
export class AppModule {}
Plnkr
Edit: Plnkr seems unhappy. StackBlitz
you can easily use this directive
usage:
<label [jsonFilter]="search">{{text}}</label>
directive
import {
AfterViewInit,
Directive,
ElementRef,
Input,
OnChanges,
SimpleChanges
} from '#angular/core';
#Directive({
selector: '[jsonFilter]'
})
export class FilterDirective implements OnChanges, AfterViewInit {
#Input() jsonFilter = '';
constructor(
private el: ElementRef,
) {
}
ngOnChanges(changes: SimpleChanges) {
this.ngAfterViewInit();
}
ngAfterViewInit() {
const value = this.el.nativeElement?.innerText.split('\n').join('');
if (!value) return;
const re = new RegExp(this.jsonFilter, 'gi');
const match = value.match(re);
if (!match || match.some(x => !x)) {
this.el.nativeElement.innerText = value;
} else {
this.el.nativeElement.innerHTML = value.replace(re, "<mark>" + match[0] + "</mark>")
}
}
}
I'm trying to build an app with ionic that reads data from a local `.json' file and uses this data to fill a page. But I'm already struggling with importing the file into the page. What I currently have is:
import { Component } from "#angular/core";
interface Entry {
name: string,
telephone: string
}
interface EntryList {
entryList: Array<Entry>;
}
#Component({
selector: 'page-list',
templateUrl: 'list.html'
})
export class ListPage {
entryList: EntryList;
constructor() {
this.load_entries();
};
load_entries () {
this.entryList = JSON.parse(
// ?
)
};
}
The .json file contains entries like:
[
{"name": "Person A","telephone": "1234"},
{"name": "Person B","telephone": "12345"}
]
I don't know how to proceed from here on. What's the right way to get my data into the app?
Please try this:
constructor(public http: HttpClient) {
this.load_entries();
};
load_entries(filePath: string) { //filePath: 'assets/test.json'
this.http
.get(filePath)
.subscribe((data) => {
console.log(data);
});
}
Of course, you have to import HttpClient first.
import { HttpClient } from '#angular/common/http';
this is a link to maps.googleapis.com. You get JSON information about the latitude and longitude in the url.
I need to read this JSON using Typescript and Angular2.
I tried a lot of different google suggestions and (among others) the following code (suggested by angular on this link):
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
// this is fired when I click on my map, this.lat & this.lng are correctly filled
getLongLatClick($event: any) {
this.lat = $event.coords.lat;
this.lng = $event.coords.lng;
this.url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+this.lat+','+this.lng+'';
console.log(this.http.get(this.url).map(this.extractData));
But when I debug in chrome, the "extractData" methode doesn't run.. It seems that the googleapis link isn't JSON for some reason
What do I have to do to read the JSON?
You should create a service that makes the http.get to get the data, similiar to :
import { Injectable } from '#angular/core';
import {Headers, Response, Http, RequestOptions} from "#angular/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class DataService{
private gmapsUrl: string = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=52.48278022207823,6.15234375';
constructor(private http: Http) {};
getAll() {
return this.http.get(this.gmapsUrl).map((response: Response) => response.json());
}
}
Cool, now you have a service that gets the data, which is also injectable. You can inject this service into any consumers you wish and consume the data. That is similar to :
import {Component, OnInit, ElementRef} from '#angular/core';
import {DataService} from "path";
#Component ({
moduleId: module.id,
selector: 'custom',
templateUrl: //your metadata,
styleUrls: //your metadata
})
export class ConsumerComponent implements OnInit{
gmapsData: any = [];
constructor(private dataService:Data) {}
ngOnInit(): void {}
private loadAllUsers() {
this.dataService.getAll().subscribe(response=> {
console.log(response.results); //
this.gmapsData = response;
});
}
}
Hope this helps -> This should give you a solid starting point.
What I haven't actually checked is the mapping between the response of the dataService.getAll() inside the consumer to the actual component property gmapsData, but you should be able to infer how to store it from the console.log(response);
You are using the wrong code in your extractData. As you can see in the JSON response:
{
"results" : [
{
"address_components" : [
{
"long_name" : "20",
"short_name" : "20",
"types" : [ "street_number" ]
}
.......
it has results, not data.
So it should be:
private extractData(res: Response) {
let body = res.json();
return body.results || {};
}
So the following should work fine (using the static url in this example):
this.http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng=52.48278022207823,6.15234375')
.map(this.extractData)
.subscribe(data => console.log(data))
Remember to always subscribe to get your response. And do consider making a service where you do the http-calls and map and then in your component call that service method and subscribe the results!
And it's good to check the network tab and see what the response looks like, and to see if you are getting a response at all.
Hope this helps! :)
I am currently using Angular2 for my application and now I want to add ng2-table to my component.
ng2-Table on Git
I am getting this error and couldn't help but ask:
angular2-polyfills.js:487 Unhandled Promise rejection: Template parse errors:
Can't bind to 'colums' since it isn't a known property of 'ng-table'.
1. If 'ng-table' is an Angular component and it has 'colums' input, then
verify that it is part of this module.
2. If 'ng-table' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA"
to the '#NgModule.schema' of this component to suppress this message.
("
</div>-->
<ng-table [ERROR ->][colums]="columns" [rows]="rows" > </ng-table>
<div class="">
"): DeviceOverviewComponent#18:10 ;
Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:(…)
In my html I got this:
<ng-table [columns]="columns" [rows]="rows" > </ng-table>
My Component is this:
import { Component } from '#angular/core';
import { Router } from '#angular/router';
import { DeviceService } from '../services/device.service';
#Component({
selector: 'device-overview',
templateUrl: 'dist/html/deviceoverview.component.html',
providers: [DeviceService],
})
export class DeviceOverviewComponent {
devices: any;
columns: any;
rows: any;
constructor(private deviceService: DeviceService, private router: Router) {
}
loadDevices() {
this.deviceService.getDevices()
.then((data) => {
this.devices = data
this.rows = this.devices
})
}
goToDevice(deviceName: string) {
this.router.navigateByUrl('/devices/' + deviceName)
}
ngOnInit() {
this.columns = [
{ title: "test", name: "id" }]
this.loadDevices();
}
}
And my app.module is this:
import { NgModule } from '#angular/core';
import { LocationStrategy, HashLocationStrategy } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { Ng2TableModule } from 'ng2-table/ng2-table';
import { AppComponent } from './components/app.component';
import { DeviceOverviewComponent } from './components/deviceoverview.component'
import { DeviceService } from './services/device.service';
import { routing } from './app.routing';
#NgModule({
imports: [
Ng2TableModule,
BrowserModule,
FormsModule,
HttpModule,
routing,
],
declarations: [
DeviceOverviewComponent,
AppComponent,
],
providers:
[
{provide: LocationStrategy, useClass: HashLocationStrategy},
DeviceService,
],
bootstrap: [AppComponent]
})
export class AppModule { }
Does anybody know anything about the Usage of ng2-table? Or is there a valid alternative, since the demo page/usage documentation is not available by now?
I found some alternatives, but lots of them had their last commit a long time ago, which might be a problem, since I am always using latest Angular2.
Thanks for reading and any hel is appreciated!
EDIT:
I've made it to the next step!
I needed to add
import {CUSTOM_ELEMENTS_SCHEMA} from '#angular/core'
#NgModule({ ...,
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
within my app.module.ts
Now I am getting the table header with the "test" column and the ID property of my row data is displayed correctly.
Even the demo from ng2-table didn't have that import.
I guess docs and demos arent made for newbes nowadays. :/
i see a typo in your html:
[colums]="columns"
It should be
[columns]="columns"
You're missing n
Plunker Example (I also tried it on local machine and it works)
You shouldn't use CUSTOM_ELEMENTS_SCHEMA
systemjs.config.js
map: {
...
'ng2-table': 'npm:ng2-table'
},
packages: {
...
'ng2-table': {
defaultExtension: 'js'
}
}
After long time I close this issue.
In my case I have these structure:
src
--app
-- app.module
-- TravelPlan
-- travel-plan.module
-- test.component
So, I was trying put the ng2-smart-table in app.module, but I was wrong. The correct is put in travel-plan.module.