Error while getting data via JSON using Http in angular2 - json

My .ts file has code :
/// <reference path="../../../../node_modules/angular2/typings/tsd.d.ts" />
import {Component,View,CORE_DIRECTIVES,} from 'angular2/angular2'
// import {provide} from 'angular2/angular2'
import {Http} from 'angular2/http';
#Component({
selector: 'renew',
templateUrl: 'static/components/library/renew/renew.html',
styleUrls: ['static/app.css'],
directives: [CORE_DIRECTIVES]
})
export class Renew{
http;
constructor( http:Http){ };
}
i have one .Json file having data in the form of arrays. i want to get data from json and want to show in the template. but whenever i use http in the constructor it returns error like following:
Cannot resolve all parameters for Renew(?). Make sure they all have valid type or annotations.
I have tried official angular2 website's plnkr for demo link here. but this is also not working for me(it seems that plnkr is for the alpha 37).
i am using angular2 44 alpha. and trying to get data in the child component.
am i doing something wrong here ?

Related

Best way to store/display data in angular

So I have a FAQ page which I have developed in angular and I have hardcoded all the data in a html file .I just wanted to know is there a better way of displaying the data like storing it in a XML/JSON/TXT file and read the file and display it or store the XML/JSON/TXT file in angular and read form it**(if storing it where to store it)**.
.Browsed for a few articles didn't find anything helpful ,any guidance will be appreciated. I am new to angular so just looking for some advice ,thanks in advance.
If your data is static I recommend storing it in a JSON file inside your angular application under the assets folder.
You can then use Angular HttpClient to retrieve the content of the file.
In this example, the file is called 'data.json' and is stored under the 'assets' folder:
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.css']
})
export class MyComponent implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get('/assets/data.json').subscribe().then(data => console.log(data));
}
}
You can find more information here.

Putting anything in the constructor of Angular component results in failure of entire page

I am trying to add something to the constructor of one of my Angular components, however, anytime I put something in the constructor, it renders the entire page blank - getting rid of all of the other components and displaying just the background.
For example - this will work.
TS
#Component({
selector: 'app-cardboxes',
templateUrl: './cardboxes.component.html',
styleUrls: ['./cardboxes.component.scss']
})
export class CardboxesComponent implements OnInit {
constructor() { }
ngOnInit(): void {}
}
And this will render completely blank - removing everything, even the other components.
TS
#Component({
selector: 'app-cardboxes',
templateUrl: './cardboxes.component.html',
styleUrls: ['./cardboxes.component.scss']
})
export class CardboxesComponent implements OnInit {
constructor(private dialog: MatDialog) { }
ngOnInit(): void {}
}
For the record, it doesn't matter what is put in the constructor - it is the same result every time. The Chrome terminal says that there is a NullInjectorError - No provider for MatDialog
Is there a reason for this, or an easy solution? I do not understand why this is happening and I really need to be able to use the constructors. Do I have to make another import somewhere? Is there a configuration I am missing?
You are trying to use angular materials. Please use this comand in console.
npm i #angular/material
Open app.module and
NgModule ({....
imports: [...,
MatSliderModule,
…]
Items adsed in constructor should be imported in module

How to load jsp page as template in component in angular 6

I want to load the external jsp page content as template in my component in angular 6 application.
#Component({
selector: 'app-conrequest',
templateUrl:'mydomain.com:port/utils/registerUser.jsp',
styleUrls: ['./conrequest.component.css']
})
In the above code, I have mentioned the jsp page url, which I want to load as a template.
Please help me on this.
Thanks,
Suresh
First of all whichever external link you are using it should "return" something.
If there is no information in return it will always gives you an error.
Lets begin your answer...
Step 1- First you need to import HttpClient and Map
import { HttpClient } from '#angular/common/http';
import 'rxjs/add/operator/map';
Step 2- and your #Component decorator should look like this
#Component({
selector: 'my-template',
template: `<div [innerHtml]="myTemplate">
</div> `})
Step 3- in your class you can import your external template like...
export class TestComponent {
private myTemplate: any = '';
constructor(http: HttpClient) {
http.get('www.abc.com/index.html', {responseType: 'text'}).subscribe(data => this.myTemplate = data);
}
}
Step 4 - Also import httpClient in RootModule
imports: [
...
...
HttpClientModule
],
That's it. Try with yours.
Thanks
Sunil Sain

Cannot recieve DATA from RESTFUL API using IONIC 2 generated provider

So, i'm currently studying Ionic 2 to make hybrid applications. I'm following a course on Udemy but the course's content about HTTP requests to WEB API's is obsolete(it's from the ionic 2 Beta). This is a long question but some of you's who are more experienced on the Ionic 2 framework can just skip to step 8 to save some time. Thanks a lot guys!
I'm trying to retrieve data from this URL:
https: //viacep.com.br/ws/01001000/json/.
It has a space after https:// because stackoverflow won't allot me to post more than one link.
But I'm missing something to save this data on a variable I created.
What I did to this point is:
1) I generated the provider which I called ConnectionService using the CLI ionic generator.
ionic g provider ConnectionService
2) Created a method called getCEP() inside the ConnectionService Provider, which makes an HTTP GET Request
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the ConnectionService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class ConnectionService {
constructor(public http: Http) {
console.log('Hello ConnectionService Provider');
}
getCep(): Promise<Response>{
let response: any = this.http.get("https://viacep.com.br/ws/01001000/json/");
console.log("Response: " + response);
let responsePromise: any = response.toPromise();
console.log("ResponsePromise: " + responsePromise);
return responsePromise;
}
}
P.S.: Here you can see i'm loggin in two steps of the request: The first one is the response before I turn it into a Promise, so I can return it to the page. The second one is after i cast it to a Promise using the toPromise() method.
3)In my view I have a button which has the (click) directive calling the method buscarCEP()
<ion-header>
<ion-navbar>
<ion-title>Teste</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button (click)="buscarCep()">Request CEP</button>
</ion-content>
4.1) My TypeScript file has imported the ConnectionService Provider and named it ConnectionService.
4.2) I declared the ConnectionService inside the #Component directive under the "providers:" label
4.3) I create an instance of Connection Provider that I call conServ on the constructor's declaration. Also I created a variable called CEP, to store the data that I pull from it.
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { ConnectionService } from '../../providers/connection-service';
/*
Generated class for the MenuTest page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-menu-test',
templateUrl: 'menu-test.html',
providers: [ConnectionService]
})
export class MenuTestPage {
public CEP: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public conServ: ConnectionService) {
}
6)Then I modify the method buscarCEP() so that it gets that conServe instance and calls the getCEP() method which makes an HTTP Request to the URL given above.
buscarCep(): void{
this.conServ.getCep().then(data =>{
console.log("DATA:" + data);
this.CEP = data;
}).catch(err => {
console.log("ERRO: " + err);
});
console.log("CEP: " + this.CEP);
}
PS.: As you can see, i'm logging three steps into the request: The data when the getCEP() method executes, a possible error called 'err' and by the end of it, the variable CEP that I created before and saved the data value to.
7)When I run the application and click on the button, I get the following screen with the console.logs:
Image of ionic page with snips of the Chrome console
8) As you can see, my logs are returning as follows:
8.1) The "Hello ConnectionService Provider" is from the console.log inside the provider's constructor, so the import of the provider is fine and it is being instantiated.
8.2) the "Response: [object Object]" is from the first console.log() inside the getCEP() method in the provider itself.
8.3) the "RespondePromise: [object Object]" is from the second console.log() inside the getCEP() method in the provider itself, after i casted the response to a Promise.
8.4)"CEP: undefined" comes from the console.log inside the buscarCEP() method, which is called after I click on the Request CEP Button
8.5)"DATA:Response with status: 200 OK for URL: https://viacep.com.br/ws/01001000/json/" comes from the console.log() inside the buscarCEP() method.
9) From this i'm taking that the getCEP() method is being able to connect to the URL, hence why the Response and ResponsePromise logs have an Object attached to them. Also the DATA log tells me that i recieved an OK Response from the server. My question is in regard to CEP: Undefined log. I can't seem to store that object in the variable I created.
I know that this is a long one but I wanted to lay all my cards on the board and explain everything as thoroughly as I could because i'm new to this framework.
Any help is appreciated, thank you for your time!
The Response object is stored in this.CEP. The issue is console.log(this.CEP) is called before the response from the HTTP request is returned within then.Promises are asynchronous.You can check the contents by doing console.log(this.CEP) within then.
So if you were to print the data in the html side, use safe navigation operator ?. e.g: {{CEP?.property}}.
A couple of issues with your code:
You should extract the json data from your response object. I suggest you do:
this.CEP = data.json();
If you want to print the contents of the object you can try console.log(JSON.stringify(data,null,2)).

How to Display Typescript code in Html

I want to display a component's code in a Html template, Not the value generated by the code but the actual code.
like this
import { Injectable } from '#angular/core';
import { Resolve, ActivatedRouteSnapshot } from '#angular/router';
import {CompetitionService} from "../shared/competition.service";
import {Observable} from "rxjs";
#Injectable()
export class TableResolve implements Resolve<any> {
constructor(private competitionService:CompetitionService) {}
resolve(route: ActivatedRouteSnapshot):Observable<> {
return this.competitionService.getTeams(route.params['id']);
}
}
This whole code like they show in stackoverflow in the question section.I tried using <pre> and <code> but none seem to work ,i am getting this error in console.
Error: Template parse errors: Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)
But if i have to escape it for all { it is problematic please help ?
Use a variable in your ts file that contains all the code and display it in html using this {{stringThatContainsAllTheCode}}
I think the simplest way is to use [innerHTML]="varContainingCode" and hold the code in the components class
<pre>
<code [innerHTML]="code"></code>
</pre>
export class AppComponent {
code = ` //type script code`
}
Or if you don't want to use this library call ng2-prism can be useful.
This is a Angular2 codeblock highlighting component library.