0
votes

I read txt file like this:

private function ReadFile():void
    {
        var loadedPage:String;
        var url:URLRequest = new URLRequest("file.txt");
        var loader:URLLoader = new URLLoader();
        loader.load(url);
        loader.addEventListener(Event.COMPLETE, loaderComplete);
        function loaderComplete(e:Event):void
        {
            loadedPage = loader.data;
            //if i trace loadedPage here it works great
            reader(loadedPage);
        }
    }

reader class is in separate file, it looks like:

public class reader
{
    var pageContent:String;

    public function reader(loadedPage:String):void
    {
        pageContent = loadedPage;
        read();
    }

    private function read():void
    {
        trace(pageContent);
    }
}

But there I get an error:

[Fault] exception, information=TypeError: Error #1034: Type Coercion failed: cannot convert "Lorem ipsum dolor sit amet, consectetur adipiscing elit

This is what file.txt contains at first line.

Why do I get this error? I do not try to convert, I just want to pass Sting to function.

1

1 Answers

1
votes

You got that error because your are trying to cast ( type conversion ) a String to your reader object.

So to avoid that you can :

  • Use an instance of your reader class. Here I should tell you that class names always start with a capital letter : Reader instead of reader. For more take a look here.

So for this case, you can do ( it's just an example, I don't see why you need this ) :

var reader:Reader;

// ...

function loaderComplete(e:Event):void
{
    loadedPage = loader.data;
    reader = new Reader(loadedPage);
}
  • Use a static function, for example read(), like this :
public class Reader 
{
    // ...

    public static function read(loadedPage:String):void
    {
        trace(loadedPage);
    }
}

Then you can write :

function loaderComplete(e:Event):void
{
    loadedPage = loader.data;
    Reader.read(loadedPage);
}

Hope that can help.