Call external function angular 2 - facebook-graph-api

I've a problem with facebook API,
I would like to call a function but I'm located in Facebook.api function so my function is not recognized because I'm encapsulated in Facebook object. Here is my code :
export class MyClass {
constructor(platform:Platform) {
}
function1(number_likes:number) {
var elem = document.getElementById('number_of_likes');
elem.innerHTML = ""+number_likes;
}
query_fan_numbers() {
var pageId = "81221197163?fields=fan_count";
Facebook.api(pageId, null)
.then(function(success) {
this.function1(parseInt(JSON.stringify(success.fan_count))); //Here's the error
}
}
My error is something like that : TypeError: Cannot read property 'function1' of null
How can I call the function1 function in my class ?

As #jonrsharpe mentioned
You can either use a fat arrow:
query_fan_numbers() {
var pageId = "81221197163?fields=fan_count";
Facebook.api(pageId, null)
.then((success)=> {
this.function1(parseInt(JSON.stringify(success.fan_count))); //Here's the error
}
}
or the the plain old javascript trick to store this in a variable to use later.
query_fan_numbers() {
var that = this;
var pageId = "81221197163?fields=fan_count";
Facebook.api(pageId, null)
.then(function(success) {
that.function1(parseInt(JSON.stringify(success.fan_count))); //Here's the error
}
}

Related

How to get anonymous contact ID in Sitecore 9.1?

How to get anonymous contact ID using Sitecore API?
I'm using this code but can't find the contact ID in xconnect DB.
using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
{
try
{
// var enumerator = client.Interactions.Where(x => x.DeviceProfile.Id == contactId).GetBatchEnumeratorSync(10);
Event ev = new Event(Guid.NewGuid(), DateTime.UtcNow) { Duration = new TimeSpan(20) };
var reference = new ContactReference(contactId);
Contact contact = client.Get<Contact>(reference, new ContactExpandOptions() { });
if (contact != null)
{
client.ExecuteRightToBeForgotten(contact);
client.Submit();
}
}
catch (XdbExecutionException ex)
{
// Manage exceptions
}
}
You can get it with the code new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N")) This is the xDB identifier which is the identifier anonymous contacts get.
Here is the code I use _contactIdentificationRepository is in a Foundation repository. _contactIdentificationRepository.GetContactReference() will get the anonymous or identified contact reference.
Call xConnect
var contactReference = _contactIdentificationRepository.GetContactReference();
using (var client = SitecoreXConnectClientConfiguration.GetClient())
{
// we can have 1 to many facets
// PersonalInformation.DefaultFacetKey
// EmailAddressList.DefaultFacetKey
// Avatar.DefaultFacetKey
// PhoneNumberList.DefaultFacetKey
// AddressList.DefaultFacetKey
// plus custom ones
var facets = new List<string> { PersonalInformation.DefaultFacetKey };
// get the contact
var contact = client.Get(contactReference, new ContactExpandOptions(facets.ToArray()));
.....
}
_contactIdentificationRepository
private readonly ContactManager contactManager;
public ContactManager Manager => contactManager;
public ContactIdentificationRepository()
{
contactManager = Factory.CreateObject("tracking/contactManager", true) as ContactManager;
}
public IdentifiedContactReference GetContactReference()
{
// get the contact id from the current contact
var id = GetContactId();
// if the contact is new or has no identifiers
var anon = Tracker.Current.Contact.IsNew || Tracker.Current.Contact.Identifiers.Count == 0;
// if the user is anon, get the xD.Tracker identifier, else get the one we found
return anon
? new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N"))
: new IdentifiedContactReference(id.Source, id.Identifier);
}
public Analytics.Model.Entities.ContactIdentifier GetContactId()
{
if (Tracker.Current?.Contact == null)
{
return null;
}
if (Tracker.Current.Contact.IsNew)
{
// write the contact to xConnect so we can work with it
this.SaveContact();
}
return Tracker.Current.Contact.Identifiers.FirstOrDefault();
}
public void SaveContact()
{
// we need the contract to be saved to xConnect. It is only in session now
Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
this.contactManager.SaveContactToCollectionDb(Tracker.Current.Contact);
}

Calling function from another function in ionic2

i want to call set function from var success function.
how to do this not able to use this.set()
getting this error http://prntscr.com/j1il36
please help
set(otp){
alert(otp);
this.otpData.otp = localStorage.getItem('otp');
}
smsRead(){
var options = {
delimiter : "OTP is",
length : 6,
origin : "ENTIND"
};
var success = function (otp) {
this.set(otp);
localStorage.setItem('otp', otp) ;
OTPAutoVerification.stopOTPListener();
}
var failure = function () {
OTPAutoVerification.stopOTPListener();
alert("Problem in listening OTP");
}
OTPAutoVerification.startOTPListener(options, success, failure);
}

Ember: Setting a component object value within a promise

I have component with a couple of properties, using a promise in the willRender hook to try and create a (pagination) object:
export default Ember.Component.extend({
pagination:null,
testing:null, // to check if this.set is ok within the promise!
willRender() {
let page = {};
let model = this.get('data');
model.get('products').then(relatedItems => {
let maxRecords = relatedItems.get('length');
relatedItems.forEach(function(item,index) {
if (item.get('slug') === itemModel.get('id')) {
if (index === 0) {
page.Prev = null;
page.Next = relatedItems.objectAt(index+1).get('slug');
}
else if (index+1 === maxRecords) {
page.Prev = relatedItems.objectAt(index-1).get('slug');
page.Next = null;
}
else {
page.Prev = relatedItems.objectAt(index-1).get('slug');
page.Next = relatedItems.objectAt(index+1).get('slug');
}
}
});
this.set('testing','hello world');
console.log(this.get('testing')); // hello world
this.set('pagination',page);
console.log(this.get('pagination')); // Object {Prev: "product-1", Next: "product-2"}
},reject => {
console.log('error '+reject);
});
}
})
In my template
{{testing}} // prints hello world
However, if I try and access {{pagination}} eg {{log pagination}}, the browser crashes with a loop printing out the object to the console.
I don't know where I'm going wrong here - any help much appreciated!
It's likely you are triggering the template to rerender causing willRender to fire over and over which causes an infinite loop in your code.
willRender is a non-standard place to do this code, init would be more standard since it only fires on initialization of the component. Even better would be to use
myInit: Ember.on('init', function(){
....
})`
instead of overriding willRender on the object.
try to check whether Object is present at specific position. i think its going undefined during iteration of for loop. try to ensure that ObjectAt is not returning undefined or null value during running of for loop.
relatedItems.forEach(function(item,index) {
if (item.get('slug') === itemModel.get('id')) {
if (index === 0) {
page.Prev = null;
if(relatedItems.objectAt(index+1) ! = undefined) {
page.Next = relatedItems.objectAt(index+1).get('slug');
}else{
page.Next == null;
}
}
else if (index+1 === maxRecords) {
if(relatedItems.objectAt(index-1) ! = undefined) {
page.Prev = relatedItems.objectAt(index-1).get('slug');
}else{
page.Prev = null;
}
page.Next = null;
}
else {
if(relatedItems.objectAt(index-1) ! = undefined) {
page.Prev = relatedItems.objectAt(index-1).get('slug');
}else{
page.Prev = null;
}
if(relatedItems.objectAt(index+1) ! = undefined) {
page.Next = relatedItems.objectAt(index+1).get('slug');
}else{
page.Next = null;
}
}
}
Please ensure that Object at is returning object.
There seems to be a few problems here, would be interested to know what your console errors are.
You don't seem to have defined itemModel so don't know how you're referencing that.
Also you can't access this from within a .then. You need to do something like this to set a component variable.
var _this = this;
promise().then(function(results) {
_this.set('testing', 'hello world');
});
you are not using , after testing:null
there should be , after testing property like that
pagination:null,
testing:null, // i use ',' after testing: null property
try to use your pagination code under init hook rather than willrender hook
init() {
//you code
},

Assign ajax result to interface inclusive methods

I'm quite new to Typescript and have a bit of a problem to get my code working. I have the following interface/class structure
interface IInterface {
id : number;
method() : string;
}
class IClass implements IInterface {
id : number;
method() : string { return "foo";}
}
Now I want to get some data from a webservice via the following call
$.get("/some/url", (data : Array<IInterface>) => {
for (var i = 0; i < data.length; i++) {
console.log(data[i].id);
console.log(data[i].method());
}
});
While this compiles perfectly fine in typescript and also all properties are set perfectly fine, I get a runtime TypeError data[i].method is not a function
So now my question: How can I cast/assign (?) this correctly, so that the methods are also available in the resulting JavaScript?
UPDATE As requested: a dump of the data I get from the webservice.
data = [{id : 1}, {id : 2}, ...]
Of course, this is a simplified example, the real classes/interfaces have some more properties (they all are assigned correctly), but also only one method (so far, when I get it working, some more will follow).
The problem is what you receive are objects which are complying to the interface, but they don't have a method property inside.
What you need to do in order to get this working is, you need to create new objects from type IClass in the reponse handler which extend the objects inside data:
$.get("/some/url", (data: Array<IInterface>) => {
return data.map((d) => return new IClass(d.id));
});
This is a common problem of converting JSON objects into instances of the classes. There are some proposals discussed here: JSON to TypeScript class instance?
Below is the solution I came up to do such deserialization:
export class Helper
{
public static DESCRIPTOR_SIGN = '$';
private static m_entityModules = [];
private static ReviveDateTime(key: any, value: any): any
{
if (typeof value === 'string')
{
let a = /\/Date\((\d*)\)\//.exec(value);
if (a)
{
return new Date(+a[1]);
}
}
return value;
}
private static RessurectValue(json: any, environments: any[]): any
{
if(json == null)
{
return null;
}
else if(Helper.IsString(json))
{
return json;
}
else if(json instanceof Date)
{
return json;
}
else if(typeof json === 'object')
{
return Helper.RessurectInternal(json, environments);
}
else
{
return json;
}
}
private static RessurectInternal(json: any, environments: any[]): any
{
var instance;
if(!json[Helper.DESCRIPTOR_SIGN])
{
instance = {};
}
else
{
instance = Helper.CreateObject(json[Helper.DESCRIPTOR_SIGN]);
if(Helper.IsUndefined(instance))
{
throw new Error('Unknown type to deserialize:' + json[Helper.DESCRIPTOR_SIGN]);
}
}
for(var prop in json)
{
if(!json.hasOwnProperty(prop) || prop === Helper.DESCRIPTOR_SIGN)
{
continue;
}
let val = json[prop];
instance[prop] = Helper.Ressurect(val, environments);
}
return instance;
}
private static CreateObject(className: string, environments?: any[]): any
{
let instance: any;
for(let e of environments)
{
var construct = e[className];
if(!Helper.IsUndefined(construct))
{
instance = new construct();
break;
}
}
return instance;
}
private static IsNumber(val: any): boolean
{
return typeof val == 'number' || val instanceof Number;
}
private static IsUndefined(val: any): boolean
{
return typeof(val) === 'undefined';
}
private static IsString(val: any): boolean
{
return typeof val == 'string' || val instanceof String;
}
/**
* Deserialize json object object into TypeScript one.
* #param json json object that must have its class name in '$' field
* #param environments list of modules containing all types that can be encountered during deserialization
* #return deserialized typescript object of specified type
*/
public static Ressurect(val: any, environments: any[]): any
{
if(val instanceof Array)
{
if(val.length == 0)
{
return val;
}
else
{
let firstElement = val[0];
if(typeof firstElement !== 'object')
{
return val;
}
else
{
let arr = [];
for (var i = 0; i < val.length; i++)
{
var element = val[i];
arr.push(Helper.RessurectValue(element, environments));
}
return arr;
}
}
}
else
{
return Helper.RessurectValue(val, environments);
}
}
}
Some notes for the above. It works based on the assumption that:
There is a parameterless constructor in every type that can be deserialized.
Every JSON object contain field '$' with its class name inside.
Sample of usage. Lets suppose yu have defined all your serializable classes in one external mode called 'Types'. Then to deserialize JSON object you write:
import * as types from './Types'
//Some code to get jsonObj that has jsonObj.$ set to "RealObject" - a type from "Types" module
let realObj = <types.RealObject>Helper.Resurrect(jsonObj, [types]);
Hope this helps.

How to call web service from flex

I have some problem with calling web service from flex. I have service with name UserService with one method string GetData(int i). I want to call this method from flex and get data. My code is here:
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
uService = new UserService();
uService.addEventListener("hello", echoResultHandler);
uService.GetData(1);
}
public function echoResultHandler(event:ResultEvent):void {
var retStr:String = event.result as String;
var retInt:int = event.result.echoInt;
Alert.show('want to play', retStr);
}
Might be my question is not difficult, but I can't understand why it does't works.. Can anybody help me?
Service code, generated by flex when I added reference to servese.
internal class _Super_UserService extends com.adobe.fiber.services.wrapper.WebServiceWrapper
{
public function _Super_UserService()
{
_serviceControl = new mx.rpc.soap.mxml.WebService();
var operations:Object = new Object();
var operation:mx.rpc.soap.mxml.Operation;
operation = new mx.rpc.soap.mxml.Operation(null, "GetData");
operation.resultType = String;
operations["GetData"] = operation;
_serviceControl.operations = operations;
try
{
_serviceControl.convertResultHandler = com.adobe.serializers.utility.TypeUtility.convertResultHandler;
}
catch (e: Error)
{ }
preInitializeService();
model_internal::initialize();
}
protected function preInitializeService():void
{
_serviceControl.service = "UserService";
_serviceControl.port = "BasicHttpBinding_IUserService";
wsdl = "http://localhost:3905/UserService.svc?wsdl";
model_internal::loadWSDLIfNecessary();
}
public function GetData(value:int) : mx.rpc.AsyncToken
{
model_internal::loadWSDLIfNecessary();
var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation("GetData");
var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(value) ;
return _internal_token;
}
}
Inherited class:
public class UserService extends _Super_UserService
{
protected override function preInitializeService():void
{
super.preInitializeService();
// Initialization customization goes here
}
}
Your UserService class never dispatches an event named "hello"; so therefore your result handler will never be fired. I think you need to add a result handler to the ASynctoken.
var call : Asynctoken = uService.GetData(1);
call.addResponder( new AsyncResponder(echoResultHandler) );
more info on the AsyncResponder and AsyncToken