I'm new in Angular, Nodejs and I was doing a CRUD app of txt files
I have to list all the files in a list, if you click one file need to display the data on a 'P'aragraph
My document component
getDocuments() - returns an array of all files in a path
getOneDOcument(name) -> get all the data of a file given "name"
getData(name) -> have to send the data to the paragraph with the id _> "paragraph_content"
getDocuments(){
this.DocumentService.getDocuments()
.subscribe(res => {
this.DocumentService.documents = res as Document[]
console.log("dentro del susbcribe");
console.log(res);
});
console.log("Fuera del subscribe");
}
getOneDocument(name : String){
console.log("NOO");
this.DocumentService.getOneDocument(name).subscribe(res => {
this.DocumentService.documentSelected = res as Document;
console.log(".");
});
}
getData(name : String){
console.log("hello name -> " , name)
// document.getElementById("paragraph_content").innerHTML = this.DocumentService.getOneDocument(name)
console.log("Before the subscrie");
this.DocumentService.getOneDocument(name)
.subscribe( (res ) =>{
//I need to change the paragraph content like this
//document.getElementById("paragraph_content").innerHTML = res.toString() Not working
console.log("Within", res);
} )
console.log("After Subscribe ")
}
Document Service
I got the arrays of the url given
getDocuments(){
console.log("Get Documents method");
return this.http.get(this.URL_API );
}
getOneDocument(name: String){
console.log("Get OneDocyment method name given: " , name);
return this.http.get(this.URL_API + `/${name}`)
}
postDocument(){
//left
}
deleteDocument(name:String){
//left
}
Document Component html
<nav>
<ul class="ds-list-unstyled" *ngFor="let document of DocumentService.documents">
<li> {{document}} </li>
</ul>
</nav>
<article>
<h2>Texto en pantalla: </h2>
<p id="paragraph_content">Needs to change with a click
</p>
</article>
And the responde that I got when I click a file is:
Thanks in advance
The XMLHttpRequest property responseType is an enumerated string value specifying the type of data contained in the response. It also lets the author change the response type.
You should set the responseType to text.
Try like this
getOneDocument(name: String){
console.log("Get OneDocyment method name given: " , name);
const requestOptions: Object = {
responseType: 'text'
}
return this.http.get(`${this.URL_API}/${name}`,requestOptions )
}
I think you problem is that you are not specifying that the data is text, that is why is trying to convert to JSON.
Try adding the responseType to the request, something like this,
getOneDocument(name: String){
return this.http.get(`${this.URL_API}/${name}`, {responseType: 'text'})
}
Related
Hello I am working on a process with React that will allow users to select a row or rows from a table by selecting check-boxes.
I need assistance with how once a row is checked, how can I store this information but at the same time if the row is unchecked I would also want to update the state.
Than when the user selects the submit button it will send the array object to the server side.
I have an empty array in my state and in the method that handles selecting a checkbox I am attempting to push the data to the array and than send the array with a form.
It appears as if the array is not being updated or I am missing something?
class TestStatus extends Component {
constructor (props) {
super(props)
this.state = {
selected: []
}
handleCheckChildeElement = (event) => {
var data = this.global.data;
data.forEach(data => {
if(data.testid === event.target.value) {
data.isChecked = event.target.checked
if(event.target.checked === true) {
this.setState({ selected: [ ...this.state.selected, data]
});
}
console.log(this.state.selected);
}
});
this.setGlobal({ data });
}
handleSubmit(event) {
event.preventDefault();
axios.post('http://localhost:5000/api/advanced_cleanup',
this.state.selected)
.then((res) => {
console.log("Sending tests");
}).catch(event => console.log(event));
}
render() {
return(
<div>
<table>
<AdvancedRows checked={this.handleCheckChildeElement}
handleCheckChildeElement={this.handleCheckChildeElement}/>
</table>
<form className="ui form" onSubmit={this.handleSubmit}>
<button
className="ui basic blue button" type="submit"
style={{ marginBottom: '5em' }}>
Submit
</button>
</form>
</div>
);
}
}
I expect to be able to select a checkbox or multiple and update the state array based on what is checked and than send that data to the server side.
After some additional research online I found the correct way with react to update the state array and than update it upon unchecking a check box.
If the targeted row is checked it will pass that rows object into the state array otherwise if the check box of the row is unchecked it will iterate over the state array and filter out the item that was unchecked.
This is the guide I used to assist me. https://scriptverse.academy/tutorials/reactjs-update-array-state.html
if(event.target.checked === true) {
this.setState({ selected: [...this.state.selected, data ] });
} else {
let remove = this.state.selected.map(function(item) {
return item.testid}).indexOf(event.target.value);
this.setState({ selected: this.state.selected.filter((_, i) => i !== remove) }); }
Expanding on my comment above.
handleCheckChildeElement = (event) => {
var data = this.global.data;
// create an empty array so that each click will clean/update your state
var checkedData = [];
data.forEach(data => {
if(data.testid === event.target.value) {
data.isChecked = event.target.checked
if(event.target.checked === true) {
// instead of setting your state here, push to your array
checkedData.push(data);
}
console.log(checkedData);
}
});
// setState with updated checked values
this.setState({selected: checkedData});
this.setGlobal({ data });
}
how can dynamic injection html element to page with next.js? that these elements Unknown type like(input, checkbox, img,...). this element specified with api that return json type like this:
[{
"id":"rooms",
"title":"Rooms",
"order":1,
"type":"string",
"widget":"select",
"data":[{
"Id":18,
"ParentId":null,
"Title":"One",
"Level":null,
"Childrens":[]
},
{"Id":19,
"ParentId":null,
"Title":"Two",
"Level":null,
"Childrens":[]
},
{"Id":20,
"ParentId":null,
"Title":"Three",
"Level":null,
"Childrens":[]
}]
},
{
"id":"exchange",
"title":"Exchange",
"order":0,
"type":"boolean",
"widget":"checkbox",
"data":[]
}]
my try is:
Index.getInitialProps = async function({req, query}) {
const res= await fetch('url api')
var elements= await res.json()
var test = () => (
<div>
{...... convert json to html elements.......}
</div>
)
return {
test
}
})
function Index(props) {
return(
<a>
{props.test}
</a>
)
}
result is null, mean nothing for presentation.
the question is, Do I do the right thing? Is there a better way?
What happens is that during the transfer of props from server to client in getInitialprops, JSON is serialized and so functions are not really serialized. See https://github.com/zeit/next.js/issues/3536
Your best bet is to convert the test data into a string of HTML data and inject it using dangerouslySetInnerHTML. An example will be:
class TestComponent extends React.Component {
static async getInitialProps() {
const text = '<div class="homepsage">This is the homepage data</div>';
return { text };
}
render() {
return (
<div>
<div className="text-container" dangerouslySetInnerHTML={{ __html: this.props.text }} />
<h1>Hello world</div>
</div>
);
}
}
The catch with this is that the string you return must be a valid HTML (not JSX). So notice I used class instead of className
You can read more about it here: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
I have a list of items where the title is a link to display a detailed view of the item. Click the title and it correctly goes to url + Id. In the Vue tolls the detail page retrieves the item with matching ID but as and array not an object and the template does not display any properties - what am I missing?
<script>
import axios from "axios";
export default {
name: "Report",
data() {
return {
report: {}
};
},
mounted: function() {
this.getReport();
},
methods: {
getReport() {
let uri = "http://localhost:5000/api/reports/" + this.$route.params.id;
axios.get(uri).then(response => {
this.report = response.data;
});
}
}
};
</script>
The template is so
<template>
<v-content>
<h1>report detail page</h1>
<p>content will go here</p>-
<h3>{{ report.month }}</h3>
<pre>{{ report._id }}</pre>
</v-content>
</template>
any comments appreciated
url + Id
It sounds like your issue is that you are receiving an array not an object.
You can pull out objects encapsulated inside arrays easily.
For example, if we had the following data:
var bus1 = {passengers:10, shift:1}
var busArr = [bus1]
which we can assert: busArr === [{passengers:10, shift:1}]
We could then pull out bus1 by referencing the index 0:
var bus1New = busArr[0]
If you want to avoid the data transformation and just output the structure you can consider a v-for in your template.
<p v-for="val in report">
_id: {{val._id}}
<br>
month: {{val.month}}
</p>
Hello I think it's easier to show partial lines of my code.
What I'm trying to do is when I input a zipcode, the right icon will show.
I'm using https://erikflowers.github.io/weather-icons/ this git.
for example: if NY weather condition says clear
weather condition in weather.pug should be like i.wi.wi-night-sleet
is it possible to add class name in icon tag from topic.js? or
can I use equal statement in pug flie like - if text=='clear' i.wi.wi-night-sleet
topic.js
router.post('/weather', function(req,res){
let url = `http://api.openweathermap.org/data/2.5/weather?zip=${req.body.zipcode}&units=imperial&appid=${apiKey}`
request(url, function (err, response, body) {
if(err){
res.status(500).send('Internal Server Error');
console.log('error: ' ,err);
} else {
if(req.body.zipcode.length != 5) {
res.render('topic/weather', {text: "Zipcode does not exist"})
} else {
let weather = JSON.parse(body)
let temp = weather.main.temp
let location = weather.name;
let day_weather = weather.weather[0].main;
let message = `It's ${weather.main.temp} degrees in ${weather.name}!`;
//below this I want to call icon tag that has a class name
res.render('topic/weather', {text: location + " : " + day_weather, weatherCondition: `i.wi.wi-night-sleet`});
}
}
});
})
weather.pug
extends ./homepage
block navigate
div.container-fluid
div.row.row-centered
p= text
//- space 넣을떄
= " "
if text
= date
div.col-lg-6.col-centered
form.form-group(action='/weather', method='post')
p
input(type='text', class="form-control", id="zipcode",name='zipcode', placeholder='zipcode')
p
button(type='submit', class="btn btn-primary btn-lg" style='margin-right: 10px;') Login
In your route just pass the identifying part of the icon you need:
res.render('topic/weather', {text: location + " : " + day_weather, weatherCondition: "night-sleet"});
Then here's what your pug template needs to look like:
i.wi(class= 'wi-' + weatherCondition)
or
i(class= 'wi wi-' + weatherCondition)
Either of those lines of pug will produce the same html:
<i class="wi wi-night-sleet"></i>
Hi am trying to make search engine with laravel and vue.js but i have no result:
this is my SearchController.php
namespace Amp\Http\Controllers;
use Amp\User;
use Illuminate\Http\Request;
class SearchController extends Controller
{
/**
* #param Request $request
* #return array
*/
public function search(Request $request)
{
$error = ['error' => 'No results found, please try with different keywords.'];
if ($request->has('q')) {
$users = User::search($request->get('q'))->get();
return $users->count() ? $users : $error;
}
return $error;
}
}
this my TopNavbar.vue:
<template>
<div>
<input type="text" v-model="keywords">
<ul v-if="results.length > 0">
<li v-for="result in results" :key="result.id" v-text="result.name"></li>
</ul>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
keywords: null,
results: []
};
},
watch: {
keywords(after, before) {
this.fetch();
}
},
methods: {
fetch() {
axios.get('api/search', { params: { keywords: this.keywords } })
.then(response => this.results = response.data)
.catch(error => {});
}
}
}
</script>
If i use only the api url then i have result and work proprely i mean if i make search with url on the browser something like this: api/search?q=XXXX then work pefect but only on browser wen i try to make search on then nothing
thank you for your help
To get the keywords sent from axios inside the controller, you would need to use
$keywords = $request->get('keywords');
In the code shared, you are looking for a request parameter named q. When you are entering the URL through the browser, you are entering the parameter with the name q. So the search works. I hope you are clear about the issue now.
So, assuming that you are handling the search method with eloquent, the controller action becomes:
public function search(Request $request)
{
$error = ['error' => 'No results found, please try with different keywords.'];
$keywords = $request->get('keywords')?? null;
if ($keywords) {
$users = User::search($keywords)->get();
return $users->count() ? $users : $error;
}
return $error;
}
For send Request as ajax you must use X-CSRF-Token or disable (exception) validate this token for this url.
For API url validate token disabled.
Read more:
https://laravel.com/docs/5.6/csrf