Problem with displaying Twitter timeline in Ionic 2

Trying to incorporate a Twitter embedded timeline into my Ionic 2 app, but facing an issue where the timeline disappears once the user navigates away from the view. Any ideas on what might be causing this issue?

<ion-header>
 <ion-navbar>
   <button ion-button menuToggle>
    <ion-icon name="menu"></ion-icon>
  </button>
    <ion-title>Social Media</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding> 
  <a class="twitter-timeline"  href="https://twitter.com/hashtag/amyawards2017" data-widget-id="837781109337436160">#amyawards2017 Tweets</a>
  <!--<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>-->
</ion-content>




export class SocialMediaPage{
  constructor(public navCtrl: NavController,
  private loadingCtrl: LoadingController,private toastCtrl: ToastController,
  private alertCtrl: AlertController,
  public twitter: TwitterService) {

  }

   ngAfterViewInit() {
            !function(d,s,id){
                var js: any,
                    fjs=d.getElementsByTagName(s)[0],
                    p='https';
                if(!d.getElementById(id)){
                    js=d.createElement(s);
                    js.id=id;
                    js.src=p+"://platform.twitter.com/widgets.js";
                    fjs.parentNode.insertBefore(js,fjs);
                }
            }
            (document,"script","twitter-wjs");
    }



}

Answer №1

Try replacing your ngAfterViewInit method with the following code snippet.

!function(d,s,id){
            var js: any,
                fjs=d.getElementsByTagName(s)[0],
                p='https';
                js=d.createElement(s);
                js.id=id;
                js.src=p+"://platform.instagram.com/widgets.js";
                fjs.parentNode.insertBefore(js,fjs);
        }
        (document,"script","instagram-wjs");

This solution worked well in my application, so it might work for you too. Good luck!

Answer №2

Make sure to replace ngAfterViewInit with ionViewDidEnter as shown below:

ionViewDidEnter() {
    !function(d,s,id){
        ...
    }
    (document,"script","twitter-wjs");
}

Remember, ngAfterViewInit is only triggered when the view is initialized, while ionViewDidEnter is triggered every time the view is accessed (navigated to from another view).

Please note that switching between different content within the same page may still result in an error (e.g. when using an ionic segment). In such cases, you will need to identify or create a suitable event for your scenario, like with ion-segments:

HTML:

<ion-segment [(ngModel)]="model" (ionChange)="segmentChanged()">

TS:

updateTwitter() {
    !function(d,s,id){
        ...
    }
    (document,"script","twitter-wjs");
}
segmentChanged() {
    this.updateTwitter();
}
ionViewDidEnter() {
    this.updateTwitter();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

TS2409 states that the return type of the constructor signature must be compatible with the instance type of the class

I'm encountering an issue with TypeScript and Angular. In this case, the foo class is a service that utilizes another service called fooService, which has a method getUser() that returns a promise of a specific type. Although the compilation seems fi ...

What is the correct method for retrieving data from response._body?

Initially, my nodejs server is sending the following response: "["name1","name2","name3"]" However, in my angular 2 service code, I have the following: return this.http.get(this.config.apiUrl + '/folder').map((response:Response)=> { ...

What is the most effective method to prompt an "input type="file" dialog using Angular and ng2FileUpload?

I'm currently implementing ng2FileUpload for drag-and-drop file uploads, but I would also like to give users the option to click on the drop area to open the file dialog. Assuming I have the following input: <input type="file" ng2FileSelect [uplo ...

A type guard for generics in TypeScript

I'm dealing with a variable that can be either of type C1[] or C2<C1>[]. How can I create a type guard for this variable? interface C<T>{ key: string; secret: T; } private isC(d: Foo[] | C<Foo>): d is C<Foo>[] { ret ...

Utilizing React-select Props Typings: A Guide

I'm currently working on creating a component that wraps the AsyncSelect, but I've run into an issue with their props having generics, and I'm not sure how to approach this. Below you'll find my code snippet: export class PipTagSelect ...

In TypeScript, use a type assertion to determine if my object is empty and does not contain any keys defined in the interface

As I review my code, I realize that I have defined an interface as follows: interface User { name: string, age: number } I also have a function written like this: function test(user: User): void { } In addition, I have created an empty objec ...

ReadOnly types in Inheritance

Currently, I am working on creating an unchangeable, nested data structure that also incorporates inheritance. To achieve this, I am using the Readonly generic type. In order to create different types within this structure, one of these Readonly types need ...

Move your cursor over a specific element to trigger an effect on another element that is not directly next to or related to it

In my current project, which is built with Angular, I am looking for a way to achieve a specific effect without using jQuery. Specifically, I would like the text inside a div element with the class title to have underline styling when hovering over an im ...

Working with TypeORM to establish two foreign keys pointing to a single primary key in a table

For my project, I am looking to establish bi-directional ManyToOne - OneToMany relationships with two foreign keys that reference the same primary key. Specifically, I have a 'match' table that includes two players from the 'player' tab ...

The challenge of ensuring type safety in abstract methods from a class by incorporating both generics and union types in Typescript

My goal is to create a base class in TypeScript that accepts a union of string types as a generic type, and then uses these strings as keys in an abstract method that utilizes a dictionary. The issue I'm encountering is that the child implementation ...

Updating text inputs in Angular can be done more efficiently using Angular Update

I need to make adjustments to an Angular application so that it can run smoothly on older machines. Is there a more efficient method for updating a text input field without using (keyup) to update after each keystroke? I haven't been able to find any ...

Is it feasible to tailor the structure of the new application directory?

Recently, I was assigned a task to explore customizing the folder structure for new apps, specifically Nest apps. After some research, I discovered that it is possible to create a "lib" folder within the "tools" directory and leverage patterns to automatic ...

What is the method for assigning the results of Array#map to a variadic tuple `[P in keyof T]: ReturnType<T[P]>`?

Attempting to devise a strongly-typed function for mapping over a uniform array of functions that yield arbitrary values. I've tinkered with both approaches, and while they do produce the expected types, I encounter issues with the return value: cons ...

Utilize generic typings to interact with the Array object

I'm facing a challenge in developing an interface that is dependent on another interface. Everything was going smoothly until I reached the Array of Objects. Let me elaborate, I have an 'Entity' that defines how a document is stored in a ...

Unable to reference an enum prior to its initialization in a React TypeScript application

I have encountered a situation in my program where I am working with numerous files containing enum definitions and some files that combine these enums together. These enums are string-enums, so there is no issue with indexing. However, when attempting t ...

'value' is connected to every single hook

Every time I try to save my work using any hook, the 'value' field changes automatically. This has been causing me a great deal of stress. I would be extremely grateful if someone could assist me with this issue. click here for image description ...

Types that depend on function input parameters

I am facing a challenge with a function: function navigateOptions(currentScreenRoute: 'addGroup' | 'addGroupOnboarding', group: GroupEngagement) { const navigationKey = currentScreenRoute === 'addGroup' ? 'addGroupPeopl ...

The transition from Ionic 5 to 6 resulted in a significant breaking change: The type 'Config' no longer contains the property 'set'

Issue: src/app/app.component.ts:43:19 - error TS2339: Property 'set' not found on type 'Config'. [ERROR] [ERROR] 43 this.config.set('backButtonText', this.translateService.instant('button.back')); Below is the ...

Tips for effectively invoking an API within a Next.js application

I've been exploring the most effective method for calling an external API within a Next.js application recently. Given my experience in developing MERN stack applications, I typically rely on axios for handling API requests and utilize it within a use ...

Error encountered: TypeScript type error in my server-side action in Next.js

Currently seeking assistance with a server action in my Next.js application. I am encountering a type error that I can't seem to identify the root cause of. This issue arises when there are three values being passed into db.insert for orderProduct, an ...