Wednesday, 28 September 2016

Building A Notepad with Dart Angular 2 : Part Four

Another step in my personal 'Learn Angular 2' project... Here's some details of what made it into v0.04.

Services are a core part of Angular (inject-able units of functionality). They are inject-able in that the responsibility of creating the service is the Angular frameworks and any object using it receives a fully configured service when that object is created.

Okay that's a bit abstract - what does it mean for np8080? Well, there are a number of methods that process the data in the text document. Let's extract all that into a text processing service class

import 'dart:math';

import 'package:angular2/core.dart';

@Injectable()
class TextProcessingService {

  String trimText(String src) {
    return src.trim();
  }

  int getWordCount(String text) {
    String workingText = text;
    workingText = workingText.replaceAll('\n', ' ');
    List words = workingText.split(' ');
    words.removeWhere((word) => word.length == 0 || word == " ");
    return min(words.length, text.length);
  }

  int getLineCount(String text) {
    return '\n'
        .allMatches(text)
        .length;
  }
}

This is a regular class other than the @Injectable() next to the class declaration.

This service can be used in any part of our application by injecting it in the constructor. Wait a second how does Angular know how to get this service for the consumer object? We let Angular know via providers statement when we are declaring a component. This can be seen in the updated StatusComponent. Note that _textProcessingService can be declared final as it is assigned once at creation time.

import 'package:angular2/core.dart';
import 'package:np8080/services/textprocessingservice.dart';

@Component(
    selector: 'text-status',
    templateUrl: 'status_component.html',
    providers: const [TextProcessingService])
class StatusComponent {

  final TextProcessingService _textProcessingService;

  StatusComponent(this._textProcessingService);

  @Input('text')
  String text;

  @Input('modified')
  DateTime modified;

  String get length => text.length.toString();

  String get wordCount => _textProcessingService.getWordCount(text).toString();

  String get lineCount => _textProcessingService.getLineCount(text).toString();
}

That's it for this time. A few other visual tweaks have gone in. Check the app out np8080.win (I though it was worth the $1 to get a domain!) and the code is on GitHub.