I'm working on an Angular 2 application, and I'm trying to use JSON data, either local/mocked or fetched via HTTP, and display it on a component. I have an injectable service that will do the fetching/mocking -
import { Injectable } from 'angular2/core';
#Injectable()
export class TestService {
testString:string = "";
testDetails: string = "";
constructor() { }
getTestDetails(): Promise<string> {
this.testDetails = {
"status": "success",
"message": "Data save successful",
"data": {
"Random_Data_1": "Random Data 1",
"Random_Data_2": "Random Data 2"
}
};
return Promise.resolve(JSON.stringify(this.propertyDetails));
}
}
And then I have a component that uses the service via Dependency Injection -
import { Component, OnInit } from 'angular2/core';
import {TestService} from "./test.service";
#Component({
selector: 'test',
templateUrl: './test.component.html',
styleUrls: []
})
export class TestComponent implements OnInit {
testDetails: string = "";
constructor(private testService: TestService) { }
ngOnInit() {
this.display();
}
display(): void {
this.testService.getTestDetails()
.then(
testDetails => {
this.testDetails = JSON.parse(testDetails);
},
errorMessage => {
console.error("Something failed trying to get test details");
console.error(errorMessage);
}
);
}
}
The component HTML -
<div class="content">
<p> Test Details </p>
<p> {{ testDetails.data.Random_Data_1 }} </p>
</div>
The problem is, the HTML is erroring out trying to display the items in the testDetails JSON. I initially used it with md-tabs, so the first try would error out, but the other tabs would read the data fine. Also, the ngOnInit would be called twice when the error occurs. I have narrowed it down to the data coming in and the object types that is causing me the headache.
I know I can create a Details class and declare testDetails of type Details, and then map the JSON data into the class, but the thing is, I want to work with generic data, and only know a few components that will be present in the data. Is there a way to read the JSON, and use the data without having to define a separate class for each scenario ?
I have a plunker with the most basic stuff set up. The actual setup runs fine on my local system up until where I try to access the JSON data in the HTML, at which point the browser throws a cryptic error. The skeleton code doesn't even run on Plunker. That said, the structure in the Plunker defines the structure of my app and the data flow. Plunker with the basic setup
What is the best way to achieve this ? What is the standard/best practice to do this ?
Throwing another option out there, since you asked about best way to achieve this. Might not be the best idea, this is subjective ;) But if I were you...
Thinking about the future, where you will use real backend, it could be nice to use mock json file. If/when you move over to a real backend, you wouldn't basically need to change anything else but the url of the requests :)
So I set up a simple example for you. Here I used Observables, but you can use Promises if you prefer that. Here's more info on HTTP if you want/need to read up on that. Most important thing is that you have the HttpModule imported in your app module.
You have your file with JSON and in your service make http-requests to that:
getTestDetails() {
return this.http.get('src/data.json')
.map(res => res.json())
}
Your display-method:
display() {
this.testService.getTestDetails()
.subscribe(data => {
this.testDetails = data;
});
}
And in the template use the safe navigation operator to safeguard null/undefined values:
<div class="content">
<p> Test Details </p>
<p> {{ testDetails?.data?.Random_Data_1 }} </p>
</div>
Here's a
Demo
As said, this is to give another approach on how to implement the things you want to achieve, and this would probably be my preferred way :)
Use
<p *ngIF="testDetails.data.Random_Data_1 "> {{ testDetails.data.Random_Data_1 }} </p>
This is because there is no data initially.Hope this helps you.
Related
service/config file:
import { Injectable } from "#angular/core";
import { SafeHtml } from "#angular/platform-browser";
#Injectable()
export class xxxxxConfig {
xxxVaultLink: SafeHtml;
whatHappensNextItemsForEmailxxx: string[];
whatHappensNextItemsForEmailSubTextxxx: string[];
constructor() {
this.xxxVaultLink = `xxx xx`;
this.whatHappensNextItemsForEmailxxx = [
`Confirmation of payment and a copy of your receipt has been emailed to you. You should receive it shortly.`,
`xxxx will send your xxxxxdocuments (xxxxx) by post within 5 days.`,
`A copy of your renewal xxxxx along with any supporting docs can be found in your
${this.xxxVaultLink} within the next 2 - 3 days.`,
];
this.whatHappensNextItemsForEmailSubTextxxx = [
`(If you wish to receive your receipt by post, please contact us on 08xxxxx)`,
`Important: please ensure that you keep your documents safe as they form the basis of your xxxx with xxx.`,
``,
];
}
I'm trying to add a link to the third item in the array above i.e. ${this.xxxVaultLink} but it shows all of the html including tags i.e. <\a href="https://www.w3schools.com" target="_blank">xxx xx</a>
Accessing it from the component below
Component file:
whatHappensNext() {
if (!this.isxxxxy) {
this.whatHappensNextItems = this.isxxxxPhoneNumber
? this.xxxxConfig.whatHappensNextItemsForEmailxxx
: this.xxxxConfig.whatHappensNextItemsForPost;
this.whatHappensNextItemsSubText = this.isxxxxPhoneNumber
? this.xxxxConfig.whatHappensNextItemsForEmailSubTextxxx
: this.xxxxConfig.whatHappensNextItemsForPostSubText;
}
}
Not sure if this makes sense but it would be great if one of you guys could tell me how to display the html/link in this config/service file
You're missing possibly the most important part, which is the template showing us how you're attempting to show these string values.
I'll take a stab in the dark and assume it's something like this:
<div>{{myText}}</div>
If you want to slap some HTML in there, try this:
<div [innerHTML]="myText"></div>
I'm learning Angular 6 and I have a List shown on my site. Now, i need to give Users of my site the possibility to add entries to that list. There's a form with 4 fields and a submit button, when Submit is clicked, the values should be stored anywhere and all the entries should be shown on the site, permanently, not just in the active session.
How can i achieve this? Do i need to include some sort of database? Or is it possible to append the new dataset to a JSON file?
Thank you in advance
EDIT: This is a training project and will only be available through the Intranet of the Company i work at, so security concerns about missing Captchas or similar things are not a factor
If you are going to use this project for long time and if number of entries is higher and you have alot of users, then you should use some data base. And if there is limited number of users and you need this app temporary then using json file is also good. Using json file will save you from database logics etc if you are not familiar with them
To SAVE some data anywhere you HAVE TO use some kind of database.
Angular is JavaScript framework. It helps to write applications. But it does nothing with server side (except, of course, CLI and other stuff which NodeJS people likes to do).
JSON is not the only way to communicate between browser and the server. But in Angular it's easiest way.
You'll need something on the server (I suppose PHP script) which will receives data from your Angular app and will send back some feedback. In the case with PHP you'd learn how to receive JSON POST ($_POST and $_REQUEST will not work)
What I advise you in terms "how to learn Angular" is go to this step-by-step tutorial https://angular.io/tutorial
Run it twice or three times and you'll understand how works Promises, Observables, communications, templates, services and all other stuff.
It is possible to append the data to the new dataset to the JSON file create a service to read that JSON file using that service so to give you the basics of reading that JSON file
Config.service.ts
#Injectable()
export class ConfigService {
private static _config: any = {}
constructor(private _http: Http) { }
load() {
return new Promise((resolve, reject) => {
this._http.get('../assets/' + 'data.json')
.map(res => res.json())
.subscribe((data) => {
console.log("inside http get of the new service");
console.log(data);
ConfigService._config = data;
resolve(true);
},
(error: any) => {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
});
});
}
// Gets a value of specified property in the configuration file
get(key: any) {
console.log("tell me the base :" + ConfigService._config['BASE_URL']);
return ConfigService._config[key];
}
}
export function ConfigFactory(config: ConfigService) {
return () => config.load();
}
export function init() {
return {
provide: APP_INITIALIZER,
useFactory: ConfigFactory,
deps: [ConfigService],
multi: true
}
}
const ConfigModule = {
init: init
}
export { ConfigModule };
add these lines in your main module
app.module.ts
import { CommonModule } from '#angular/common';
import { ConfigModule, ConfigService } from './config-service';
providers:[
ConfigService,
ConfigModule.init(),
]
Then, you can inject this service on any component or service that wants the data
Also, you have to add an assets folder under your app folder and place the data.json there.
In my website on login,i get a confirmation and a token which i need to store and pass as a property throughout all the pages.I am able to receive the token,but i am unable to store the value for the token and store it as a state value.
Here is the code i have tried so far.
import React from 'react'
import ReactDOM from 'react-dom'
import {Login_Submit_style,Login_button_style,Login_text_field_style,
password_style,para_login_style} from './style'
import Supers from 'superagent'
class Login extends React.Component
{
constructor(props)
{
super(props);
this.state={username:'',password:''}
this.Login_data_password=this.Login_data_password.bind(this)
this.Login_data_username=this.Login_data_username.bind(this)
this.MainRedirect=this.MainRedirect.bind(this)
this.api_call_login=this.api_call_login.bind(this)
}
Login_data_username(e)
{
this.setState({username:e.target.value})
}
Login_data_password(password)
{
this.setState({password:password.target.value})
}
MainRedirect()
{
window.location = '/main';
}
api_call_login()
{
Supers.post('http://127.0.0.1:8000/user_ops/user_login/')
.send({'username':this.state.username,'password':this.state.password})
.then(response => response.json())
.then(responseData=>{
console.log(responseData);
})
}
render()
{
return(
<div style={{background:'yellow'}}>
<div>
<h1 style={{marginLeft:550}}>Login Page</h1>
<div>
<p style={para_login_style}><b>Username</b></p>
<input type="text" style={Login_text_field_style} onChange={this.Login_data_username}/>
<h2>{this.state.username}</h2>
</div>
<div>
<p style={para_login_style} ><b>Password</b></p>
<input type="password" style={password_style} onChange={this.Login_data_password}/>
</div>
<div>
<button style = {Login_Submit_style} onClick={this.api_call_login}> Log in </button>
</div>
</div>
</div>
)
}
}
This is the Format in which i get the response:
{"Successful_Login": "True", "token": "d278f30445aa0c37f274389551b4faafee50c1f2"}
So ideally i would like to store the values for both the keys returned from the json output.Adn when i use response.body,i am able to get the data in the above format.
I don't know if this will be helpful to you, but I'll try.
Things like XHR calls from a browser to an API are done asynchronously. What you get back is a promise that will execute a function you give it when the call to the API is completed. Your code rightly has a callback function.
However, I don't think that callback function can call setState, because I think (I might be wrong) React wouldn't like it.
I use Redux for React as a way of storing stuff that the rest of the app can just grab when it needs it. Better still, Redux is integrated into React in such a way that whenever this central database is updated, any component that pulls in a piece of data from it (via props) gets updated (re-rendered) automatically.
I think I should point you to the documentation for Redux for more information. There are alternatives to Redux, too.
Good luck, and ask more questions if you get stuck.
In order to set a new state with the values from a json response, I ideally call this.setState right in your promise response.
api_call_login()
{
Supers.post('http://127.0.0.1:8000/user_ops/user_login/')
.send({'username':this.state.username,'password':this.state.password})
.then(response => response.json())
.then(responseData=>{
this.setState({
Successful_Login: responseData.Successful_Login,
token: responseData.token
})
}
state will be updated when response arrives.
If possible try to use lowercase or camelCase to your keys.
It would be great if you could post link where we can see what exactly is going on, but the way I understand this you would have to add .set('Accept', 'application/json') in your request to get correct json. So, your code should be like:
Supers.post('http://127.0.0.1:8000/user_ops/user_login/')
.send({'username':this.state.username,'password':this.state.password})
.set('Accept', 'application/json')
.then(response => response.json())
.then(responseData=>{
console.log(responseData);
})
Since I cannot test, you would have to look if it works. Alternatively, I would suggest you to try using superagent
Let me know if it helps!
I'm working on my first complicated React app and I am making a request to a movie API. My site allows the user to do a search in a searchbar for whatever movie, show, actor, etc... that they are searching for. I'm pulling the user's search query and inserting it into an api request like this:
export const getDetails = (id) => {
return new Promise(function(resolve, reject) {
axios.get(`https://api.themoviedb.org/3/movie/` + id +`?api_key=&language=en-US`)
.then(function(response) {
resolve(response)
})
.catch(function(error) {
reject(error)
})
})
}
I'm able to get the data like this and console.log it:
import React, { Component } from 'react';
import Header from '../header';
import {Link} from 'react-router-dom';
import axios from 'axios';
import Footer from '../Footer.js';
import Searchbar from '../header/searchbar.js';
import List from '../results/list';
import {getDetails} from '../api/getDetails';
class Detail extends Component {
constructor(props) {
super(props);
this.state = {
id: this.props.match.params.id,
result: null,
error: false,
}
}
componentWillMount() {
getDetails(this.state.id).then(function(response){
this.setState({result: response});
console.log(response.data.original_title);
console.log(response.data.homepage);
console.log(response.data.popularity);
console.log(response.data.release_data);
console.log(response.data.overview);
}.bind(this)).catch(function(err) {
this.setState({
result:"There was a problem loading the results. Please try again.",
error: true
})
}.bind(this))
}
render() {
return(
<div>
<Header/>
<div className="details-container">
<h2>Details: </h2>
</div>
</div>
)
}
}
export default Detail
Console.logging it in the componentWillMount function successfully logs the data but I am not able to access the data in the render function via something like {response.data.orginal_title). How would I render the data being logged in componentWillMount?
TLDR; You can access your state variables from within your render function via this.state. Something like: console.log(this.state.result.data.origin_title) outside of the jsx and {this.state.response.data.orginal_title} inside the jsx.
P.S. You are using the correct this.
The following are picky recommendations and explanations, feel free to disregard.
It's recommended to make requests for data in componentDidMount. That can be read here in the docs for componentDidMount.
You're using arrow functions already in your get details function, if you convert the rest of your functions to arrow functions you no longer have to explicitly bind this to each one; it's automatically set be the this of it's parent. See the "No Separate This" section in the MDN docs
If you don't need any of the header information I would save response.data into your state so you don't have to type as much when you want to access the data. this.state.result.original_title vs this.state.result.data.original_title. That's just me and I'm lazy.
axios does return a promise like Eric said so you don't actually need to wrap it in the extra promise. You can just straight up return it and since arrow functions automatically return one line expressions you can spiff that up into a one liner:
export const getDetails = id => axios.get(`https://api.themoviedb.org/3/movie/${id}?api_key=&language=en-US`)
Finally you should be able to access the data you've stored in your state from your render function as mentioned in #3 above. Outside of the JSX you can console.log it like normal console.log(this.state.result), inside your JSX, however, you will need to make sure you escape with {} like: <div>{this.result.original_title}</div>
Small working example here: https://codesandbox.io/s/zqz6vpmrw3
You can simply use
{this.state.result}
inside the render.
I am in process on creating a small poc to try whether is it possible to load components according to a given json data structure. json will provide and array of component selectors. I tried a small example according to the reference materials i found via online. I used the "componentFactoryResolver" which is recommended way by Angular
I basically create couple of components and registered it with the entrycomponent decorator as follow in my module
entryComponents: [PersonalDetailsComponent, ContactDetailsComponent],
and in my app component i use the following code
#ViewChild('dynamicInsert', { read: ViewContainerRef }) dynamicInsert: ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
ngAfterViewInit() {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(PersonalDetailsComponent );
const componentFactory2 = this.componentFactoryResolver.resolveComponentFactory(ContactDetailsComponent);
this.dynamicInsert.clear();
this.dynamicInsert.createComponent(componentFactory);
this.dynamicInsert.createComponent(componentFactory2);
}
and as you see i have to create component for each and every component i use. but having this an inside a loop might not be the best way to do it. i would much appreciate if any one could give me some heads up to do it in a proper way.
my actual json would look like something like this
{
"step":"1",
"viewed":false,
"stepDependant":{
"parentComponent":null,
"childComponent":null,
"varMap":null
},
"widgets":[
{
"Component":"shipper",
"inputs":[
{
"ServiceLine":"Export"
}
],
"outputs":[
],
"name":"Shipper Details"
},
{
"Component":"shipper",
"inputs":[
{
"ServiceLine":"Export"
}
],
"outputs":[
],
"name":"Consignee Details"
},
{
"Component":"status-of-shipment",
"inputs":[
],
"outputs":[
],
"name":"Status of Shipment"
}
]
}
much appreciate your inputs
As you have already found the componentFactoryResolver is the correct way to create components dynamically from code.
With this approach what I would do in your case is create a map or service that maps the component selectors to component types. This way you can then quickly lookup the type when you are creating the dynamic components from the JSON data. From the types you then resolve the factory and then add the components like in your sample.
If you have a predefined set of components that are known another alternative would be to define them all as <ng-template> in the parent component like this:
<ng-template #shipper><shipper ></shipper></ng-template>
<ng-template #statusOfShippment><status-of-shipment ></status-of-shipment></ng-template>
Then you can get the templates in the component by using the #ViewChild decorator.
#ViewChild('shipper')
shipperTemplate: TemplateRef<any>;
#ViewChild('statusOfShippment')
statusOfShippmentTemplate: TemplateRef<any>;
And then you can create the components in a simmilar fashion than with the factory.
this.dynamicInsert.createEmbeddedView(shipper);
this.dynamicInsert.createEmbeddedView(statusOfShippment);
What is good about this approach is that you can still have classic template binding and send a different context object to every template.
<ng-template #shipper><shipper [ServiceLine]="ServiceLine"></shipper></ng-template>
this.dynamicInsert.createEmbeddedView(shipper, {ServiceLine:"Export"});
This way you could directly send an object created from your JSON and configure the component bindings. If you use the component factory you need to set everything from code manually.