Okey so I've got a little problem with MailChimp response. So here is the thing.
I want to check the status of the subscribed user. I have the PHP code which is works fine and i have the code which is also works fine so I get the response BUT I can't use the response after it. So here is the codes:
I have a MailService provider which contain this function:
postCheck(post: {email: string}): Observable<any>{
const email = JSON.stringify(post);
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-urlencoded');
return this.http.post('http://localhost:8100/getapi', email, {
headers: headers
}).map(res => {
console.log(res.json())
return res.json(); //add this line
});
}
In the main page I have this function:
sendCheck(email: string){
this.mailservice.postCheck({email: email})
.subscribe(
response => this.response = response.status,
error => console.log(error)
);
}
In the main page html when i call <p>{{ response }}</p> it write out 'pending' or 'subscribed'. But after it when I try console.log(this.response); it write out nothing so in the code I can't really do the checking.
From what I can gather, you want to do something with your response after the data has arrived. This you need to do inside the subscription, to ensure that the data is available. So something like this:
sendCheck(email: string){
this.mailservice.postCheck({email: email})
.subscribe(response => {
this.response = response.status;
// here the value has been set to response, so do what you want
this.doSomethingWithResponse();
)};
}
doSomethingWithResponse() {
if(this.response == 'subscribed') {
// do stuff
}
}
Related
I am using Postman to make POST request to API and save data to DB and I am getting as response {message:"Contact created successfully"}. BUT in Angular I don't get any response. What I am doing wrong?
I have provided a piece of my code below.
Angular Service
add(contactItem: any){
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
const contactApiUrl = "url to api/addContact.php";
return this.http.post(contactApiUrl,contactItem, httpOptions).pipe(
map( (response: any) => { console.log(response); }),
catchError(this.handleError)
);
}
Contact.component.ts
//here from the form I pass the data to service add()
onSubmit(contactData){
console.log(contactData);
this.contactService.add(contactData).subscribe();
//this.contactLst = this.contactService.get();
}
addContact.php
//more code here
// create the product
if($contact->create()){
// set response code - 201 created
http_response_code(201);
// tell the user
echo json_encode(array("message" => "Contact was created."));
}
// if unable to create the contact, tell the user
else{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo json_encode(array("message" => "Unable to create contact."));
}
Any help is welcome.
You're not actually returning the response. You are only logging it:
add(contactItem: any){
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
const contactApiUrl = "url to api/addContact.php";
return this.http.post(contactApiUrl,contactItem, httpOptions).pipe(
map( (response: any) => response ), // <- return response
catchError(this.handleError)
);
}
To call it, you need to specify what happens in your subscribe callback:
//here from the form I pass the data to service add()
onSubmit(contactData){
console.log(contactData);
this.contactService.add(contactData).subscribe( r => console.log(r) );
//this.contactLst = this.contactService.get();
}
So I have a josn object which has an array of objects which I want to send to a react native app through https but the problem is that I get null in react native
The code of the php :
<?php
class Product {
// Properties
public $title;
public $price;
}
header('Content-Type: application/json');
$ProductList =array();
$aa=$a->{'shopping_results'};
foreach($aa as $y => $y_value) {
$product = new Product();
$product->{'title'} = $y_value ->{'title'};
$product->{'price'} = $y_value ->{'price'};
array_push($ProductList,$product);
}
echo $x=json_encode(array('listx' => $ProductList),JSON_UNESCAPED_UNICODE);// the JSON_UNESCAPED_UNICODE for the Arabic letters
?>
When I try to view the content of this json on the browser this is what I get
https://i.stack.imgur.com/gXT4X.png
The react native code
await fetch(URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
// , body: JSON.stringify({ name: "tea" })
})
.then((response) => response.text()) //tried .json() got JSON Parse error: Unexpected EOF
.then((responseJson) => {
console.log(responseJson);//This prints blank
console.log("hi");
this.setState({ output: responseJson });//nothing shows
})
.catch((error) => {
console.error(error);
});
Note: I tried to receive a text from HTTPs request and it worked (The connection is fine)
You need to set HTTP headers, methods in your PHP code so as to accept requests from your react native app (basically I'm telling you to implement REST APIs). If already implemented, just make sure you are giving the correct endpoint in your react-native's fetch URL. And one more thing, when you are trying to retrieve data from the server make sure to set method: 'GET'.
If you're a beginner/ don't have prior knowledge about REST APIs, then here's a reference for you : https://www.positronx.io/create-simple-php-crud-rest-api-with-mysql-php-pdo/ I'm sure it'll give you some basic idea about your need.
I am posting data to Laravel and expect a success response, but it catches the exception TypeError: Network request failed. Using get methods and login post methods using Laravel passport works all fine.
Adding 'Content-Type': 'application/json' to headers creates Network request failed for the login methods.
Postman returns valid errors or success, so works totally as expected.
Debugging showed that the request has been sent to Laravel and routing is correct as Visual Studio Code debugger stops at a breakpoint at return response.
public function postMessages()
{
...
return response()->json(['success' => 'success'], 200);
}
Route::middleware('auth:api')->group(function () {
Route::post('messages', 'Api\ChatController#postMessages');
});
export const fetchApi = async (endPoint, method = 'get', body = {}) => {
const accessToken = authSelectors.get().tokens.access.value;
const accessType = authSelectors.get().tokens.access.type;
let headers = {
...(accessToken &&
{
Authorization: `${accessType} ${accessToken}`
}
)
};
let response;
if (method=='get' || Object.keys(body)==0 ) {
response = await fetch(`${apiConfig.url}${endPoint}`, {
method: method,
headers: headers
});
} else {
var formData = new FormData();
Object.keys(body).forEach(type => {
formData.append(type, body[type]);
});
response = await fetch(`${apiConfig.url}${endPoint}`, {
method: method,
headers: headers,
body: formData
});
console.log('fetch response: ' + JSON.stringify(response));
}
let responseJsonData = await response.json();
return responseJsonData;
}
export const postMessages = (eidug, type, name, messages) => fetchApi('/message', 'post', {
'eidug': eidug,
'type': type,
'name': name,
'messages': messages
});
I expect a response without any exception like Postman. What can be going wrong?
Have you enabled CORS in the backend? Once open inspect->network and then run fetch. Show if there are any errors.
In my ionic app I tried passing array returned from a php api to another page but it was not passing any values
In user.html page I have the button that when click pass the value to the next page
<button ion-button icon-only (click)="goToResult()">
<ion-icon ios="ios-log-out" md="md-log-out" class="user"></ion-icon> Next
</button>
userHome.ts
ngOnInit(){
this.phone = this.navParams.get('phone');
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let options = new RequestOptions({ headers: headers });
let data = {
phone: this.phone
};
let loader = this.loading.create({
content: 'Loading Page Contents',
});
loader.present().then(() => {
this.http.post('http://mypro.com/eApi/retrieve.php',data, options)
.map(res => res.json())
.subscribe(res => {
loader.dismiss()
this.items=res.server_response;
console.log(this.items);
});
});
//this.navCtrl.push(PostPage, data);
}
On the same page, this is the push nav I tried passing the values through
goToResult(){
console.log(this.items);
this.navCtrl.push(PostPage,
this.postList = this.items
)
}
In post.ts, I added this to the contructor
this.navParams.get(this.postList);
then in my post.html
<ion-title *ngFor="let post of postList">{{post.Name}}
</ion-title>
Please, how can I pass the return values from the api to another page?
Thanks.
So if you check ionic doc example you will see that you need to pass data using json object and use its key to retrieve data, try this approach:
In your first component:
this.navCtrl.push(PostPage,
{ postList: this.items }
)
In receiving component constructor;
this.postList = this.navParams.get(“postList”);
If still struggle please share full code, but this should be easy fix;)
you can do like this
goToResult(){
console.log(this.items);
this.navCtrl.push(PostPage, {postList = this.items})
}
In post.ts, you can get value by
this.navParams.get('postList');
I am posting data to Dynamics CRM via SOAP on my PHP server with cURL. After this is done it is giving the entity GUID in the form of a HTTP Response header. When attempting to access this via my angular factory and $http.
My header is exposed and is able to be viewed in Chrome Developer tools and gives me the GUID I need.
The code for accessing the promise data is as follows:
$http({
method: 'POST',
url: url,
data: formData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data, headers) {
var array = [];
array.data = data;
array.headers = headers('EntityId');
console.log(array.headers);
deferred.resolve(array);
})
return deferred.promise;
//etc
The error I get is:
headers is not a function()
I can however, access some header result such as a status 200 code by using:
array.headers = headers;
But I need to access my custom header. Any ideas on how I can achieve this?
As per Deprecation Notice on https://docs.angularjs.org/api/ng/service/$http
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
the preferred way would be:
$http.get('/someUrl')
.then(function(response){
var array = [];
array.data = response.data;
array.headers = response.headers('EntityId');
});
As Andy said already, headers is the 3rd parameter of the success callback. So you will have to do this:-
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
})
I wasn't going to add this as an answer but doing this as I wanted to add that headers is indeed a function.
In my project, I did the below and saw function logged out as type in console. The function returns the value of the header item corresponding to the name passed, if no parameters are passed, returns an object containing all headers.
login(user) {
return this.$http.post(this.url, user)
.success((data, status, headers, config) => {
console.log(typeof headers, 'headers'); => prints function
console.log(headers(), 'headers'); => if you don't pass anything, returns an object containing all headers.
return response;
});
}
Excerpt from the angular code.
function headersGetter(headers) {
var headersObj;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
var value = headersObj[lowercase(name)];
if (value === void 0) {
value = null;
}
return value;
}
return headersObj;
};
You parameters for success are incorrect. headers is the third parameter.
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Check "Usage" section in https://docs.angularjs.org/api/ng/service/$http for reference.
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise.
The response object has these properties:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers –{function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
Angular version == 1.3.5 , Suppose header value has been set "X-AUTH-TOKEN = 'eyJwYXNzd29yZCI6ImFkbWlu'" in Application Security class after authentication.
$scope.postData = "{\"username\" : username , \"password\": password ,\"email\" :email}";
$http({
method: 'POST',
url: '/API/authenticate',
data: postData,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Login-Ajax-call": 'true'
}
})
.then(function(response) {
if (response.data == 'ok') {
$cookies['X-AUTH-TOKEN']=response.headers('X-AUTH-TOKEN');
// below put,put,putObject Cookies value is valid for Angular version >= 1.4
// $cookies.putObject('X-AUTH-TOKEN',response.headers('X-AUTH-TOKEN');
window.location.replace('/');
}
else {
// Error Message...
}
});