bind remote data from php laravel into angular front-end - php

I just started building my backend in PHP laravel. What I'm doing is receiving data from a service and I'm trying to display it inside the view but errors.
dataservice.ts
getData() {
const headers = this.getHeaders();
const list = this.http.post('tespapi/data', {
pageSize: 10,
page: 1
},{headers});
return list.pipe(tap(_ => {
}));
}
Component
ngOnInit() {
this.callServices.testCall().subscribe( data => {
this.userList = data.result.data;
});
DATA Structure from Service
{"status":"ok","code":200,"message":"Names retrieved successfully","result":{"current_page":1,"data":[{"id":32,"fullname":"Larson King","description":null,"category":{"id":12,"name":"Purple"},"unit":{"id":12,"name":"group"},"status":{"id":2,"name":"maximum level"}}],"first_page_url":"http://sample.apitest/view?page=1","from":1,"last_page":3,"last_page_url":"http://http://sample.apitest/view?page=3","next_page_url":"http://sample.apitest/view?page=2","path":"http://sample.apitest/view","per_page":1,"prev_page_url":null,"to":1,"total":3}}
The data needed want is found in result.data
When I do data.result.data an error displays Property 'result' does not exist on type 'Object'
HTML
<div *ngFor="let item of userList">
{{item.fullname}} - {{item.descripition}}
</div>

You can do it as below.
ngOnInit() {
this.callServices.testCall().subscribe( (data: any) => {
this.userList = data.result.data;
});
}

Related

Angular HTTP POST request doesn't create anything

I'm using Angular with PHP and trying to post an object. Request status is 200, but $_POST array is empty. Data I'm sending is a valid JSON Object.
sendTweet(){
if(!this.username || !this.tweet){
alert("Enter username or tweet");
return;
}
const newTweet:Tweet = {
username: this.username,
tweet: this.tweet
}
//Call Service
this.testService.postTweet(newTweet).subscribe((response)=>{console.log(response)},
(err:any)=>{
console.log(err.message);
});
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
postTweet(tweet:Tweet):Observable<Tweet>{
const url = `${this.apiUrl}/?page=submit&action=add`;
return this.http.post<Tweet>(url,tweet, httpOptions);
}
PHP:
if (isset($_POST['tweet'])&&isset($_POST['username'])) {
//Sending tweet to the db
} else{
print_r($_POST);
}
i dont know if its a backend problem with php but in my project i have it a little bit diferent (i am using .net core for backend)
for example in my project:
//service component WebScrapLinkService
get(): Observable<Any[]> {
return this.http.get<Any[]>(this.url)
.pipe(map(res => res));
}
//main component
getRegisters() {
this.getProductsSub = this.crudService.get()
.subscribe(data => {
this.registers = data;
})
}
//variables
public registers: Array<object> = [];
//the service goes in the constructor
private crudService: WebScrapLinkService
this works fine for me, i hope it is useful for you
It was just me not knowing that in PHP you have to parse HTTP_RAW_POST_DATA in order to get the data.

Vuex Laravel Loads all data

I've been trying to load all of my data when the time I log in. Currently, I've only managed to display data through the console through vuex file. I just want to achieve this because wherever it loads all data when login, it will easier for me to call every function on every page.
I think the first step is to display it on vue devtools?
This is what I've tried.
I have this file on my "./store/modules/currentUser.js"
import axios from "axios";
const state = {
};
const getters = {};
const actions = {
loadEmployee({}){
axios.post(BASE_URL + '/transportation/driver/autoComplete').then(response => {
console.log(response.data); // how to pass result to devtools?
});
}
};
const mutations = {};
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
Login.vue
<script>
export default {
data () {
return {
listdata:[]
}
},
methods: {
login() {
this.$store.dispatch('currentUser/loadEmployee', this.listdata);
}
}
}
</script>
This is my vuedevtools looks like
And I want to fetch all data on listdata array vue devtools
If you are using vuex, you should probably load state in dev tools.
However, your issue is caused by not having a mutation, so you never update the state.
import axios from "axios";
const state = {
transansportDrivers: []
};
const getters = {};
const actions = {
loadEmployee({}){
axios.post(BASE_URL + '/transportation/driver/autoComplete').then(response => {
commit('setTransportDrivers', response.data)
});
}
};
const mutations = {
setTransportDrivers: (state, drivers) => {
state.transansportDrivers= drivers;
},
};
export default {
namespaced: true,
state,
getters,
actions,
mutations
}

use dynamic params for axios requests

axios.get("/api/session/" + this.roomId)
Above is a snippet from my axios call that uses my api.php route ('/api/session/{id} that loads through the controller the requested specific room => /api/session/3 is room 3).
Currently, this snippet is harcoded and always uses integer 1 for 'this.roomId'.
I did that, in oder to check if my vue is even working fine.
My question is now, how am I able to use a dynamic param for my prop roomId?
so I can always say something like
.get/.post('url', $id) ?
If you're passing the roomId as a prop into the component then you need to handle the change in the parent component. For that I'd need a bit more context on where the room-ids come from and how you select the room-id there.
If you have this part down, then you'll want to watch changes on the roomId prop and re-fetch the data when ever it changes. You can do something like this in your room component:
<script>
import axios from 'axios'
const props: {
roomId: {
type: Number,
required: true
}
}
export default {
props,
data() {
return {
room: null
}
},
methods: {
async fetchRoom() {
try {
const response = await axios.get(`/api/session/${this.roomId}`)
this.room = response.data
} catch (err) {
// - handle error
}
}
},
watch: {
roomId: {
immediate: true // so it's executed when component is created
handler: function () {
this.fetchRoom()
}
}
}
}
</script>

Retreive Html form value in a PHP script using an Angular Service

I have an Angular 5 App with a contact form and I want to be able to retreive data from this form via a service in my PHP Script.
Here is my html
contact.html
<div class="">
<input [(ngModel)]= "subjet" name="subjet" type="text">
<label for="">subject</label>
</div>
When I click on my from button I call a function sendmail(subject) in the same component.
contact.component.ts
export class ContactComponent implements OnInit {
constructor(private sendMailService:SendMailService) { }
sendmail(subjet):void{
this.sendMailService.performGetEx().subscribe( (v =>
console.log('value: ', v)),
(e => console.log('error: ', e)),
(() => console.log('the sequence completed! :' ,subjet)));
}
And finally my service :
Injectable()
export class SendMailService {
private url = 'assets/php/sendmail.php'
constructor(private http:HttpClient) { }
performGetEx():Observable<any>{
return this.http.get<any>(this.url,
{
responseType: 'text' as 'json'
});
}
This service is the one that use the PHP Script but I can't find a way to retreive my subject value in my PHP Script.
When I do something like that $sujet = $_POST['sujet'];it doesn't work. It could have worked if my script was in the same folder as my contact component but it's not the case.
Do you know how I can do It ?
UPDATE 1 :
This link could be helpful, it might be the solution for people that have this issue : Angular HTTP post to PHP and undefined
Im my case when I do the following :
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$subject = $request->subject;
I have an error because my $postdata variable is empty ! Still don't know why
UPDATE 2 :
Like #Simos said I checked and I didn't see the data sent from Angular in my network.
So I changed my SendmailService class method from get to post.
Injectable()
export class SendMailService {
private url = 'assets/php/sendmail.php'
constructor(private http:HttpClient) { }
performGetEx():Observable<any>{
return this.http.post<any>(this.url,
{
responseType: 'text' as 'json'
});
}
I get an other error HttpErrorResponse SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse.
I already had this error before and had to add the reponseType: 'text' as 'json' in order to avoid it...And now it don't work with the post method....

how to use Directus with gatsby

How is it possible to use the Directus data in getsby.js
I've setup a Directus app, and added tables and data/columns but I have no clue how to use it in gatsby.js, I have build a template like this in jsx:
const path = require('path')
exports.createPages = ({ boundActionCreators, graphql }, { urlPrefix }) => {
const { createPage } = boundActionCreators
return new Promise((resolve, reject) => {
resolve(
graphql(
`
{
allDirectusPost {
edges {
node {
id
title
author
content
}
}
}
}
`
).then(result => {
if (result.errors) {
console.error('GraphQL query returned errors')
reject(result.errors)
}
result.data.allDirectusPost.edges.forEach(edge => {
try {
let node = edge.node
let path = `posts/${node.id}`
createPage({
path,
layout: 'index',
component: path.resolve('src/templates/post.jsx'),
context: {
post: node,
},
})
console.log(`Generated page '${path}'`)
}
catch (error) {
console.error(`Failed to generate page posts/'${path}': ${error}`)
}
})
})
)
})
}
and I have a homepage static site in gatsby.js like this
import React from 'react'
import Link from 'gatsby-link'
// import postsTemplate from '../templates/post.jsx'
const IndexPage = () => (
<div>
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.000</p>
<p>Now go build something great.</p>
<post />
<Link to="/page-2/">Go to page 2</Link>
</div>
)
export default IndexPage
how do I call the directus data in that gatsby file?
For each item in your Directus table, a new page will be created based off the src/templates/post.jsx component. This will be a completely separate set of pages to the IndexPage.
The steps to source pages from Directus is very similar to the steps to source pages from Markdown. I recommend you read https://www.gatsbyjs.org/docs/adding-markdown-pages/ one more time (though it looks like you did read it, since your gatsby-node.js code looks like it was borrowed from there). In posts.jsx, instead of querying markdownRemark(frontmatter: { path: { eq: $path } }) you want to query allDirectusPost(edges: { node: {id: {eq: $path } } }).

Categories