Angular service helps in resolving concatenate error by utilizing good practices

I encountered a problem while trying to set a URL with multiple arguments. Here is the code snippet that I attempted, but it did not work as expected:

@Injectable()
export class MapService {
    ign : string = 'https://wxs.ign.fr/secret/geoportail/wmts?';
    ignEnd = '&tilematrixset=PM&tilematrix={z}&tilecol={x}&tilerow={y}';
    ignSat = this.ign + 'layer=ORTHOIMAGERY.ORTHOPHOTOS';
    this.ignSat = this.ignSat + '&tilematrixset=PM';
    this.ignSat = this.ignSat + '&Service=WMTS';
    this.ignSat = this.ignSat + '&Request=GetTile';
    this.ignSat = this.ignSat + '&Version=1.0.0';
    this.ignSat = this.ignSat + '&Format=image%2Fjpeg' + this.ignEnd;

    private LAYER_IGN_SATELLITE = {
        id: 'ignsatelite',
        name: 'IGN Satellite',
        enabled: false,
        layer: tileLayer(this.ignSat, {
            maxZoom: 20,
            attribution: 'IGN'
        })
    };

    ...
    constructor() {}
    ...

}

Upon running the code, I received the following error message:

Unexpected token. A constructor, method, accessor, or property was expected.ts(1068)

EDIT

In an attempt to troubleshoot, I tried the following fixes:

ignSat = ignSat + '&style=normal';

And also:

ignSat = this.ignSat.concat('&style=normal');

Lastly, I attempted:

this.ignSat = this.ignSat.concat('&style=normal');

https://i.sstatic.net/5WAhL.png

https://i.sstatic.net/mL9aP.png

Answer №1

Within the boundaries of a class, but outside of any specific method, you have the ability to define and potentially initialize fields. It is not permissible to redefine or reinitialize fields in this context, nor can you include arbitrary JavaScript or TypeScript statements:

class Foo {
    bar: string | undefined; // field declaration
    baz = "hello"; // field declaration and initialization

    bar = ""; // error! Cannot redeclare or reinitialize a field
    console.log("oops"); // error! Not allowed to write random code here
}

The errors you may encounter indicate that the TypeScript compiler struggles to interpret your code as either field or method declarations. For instance, it might mistakenly identify console as some member declared within Foo, leading to confusion with subsequent lines.

If you require more complex processing for a field beyond a single initializer line, it's advisable to handle such operations inside the constructor method. Remember, when working within methods, access fields by referencing them as properties of this:

class Bar {
    bar: string | undefined;
    baz = "hello";

    constructor() {
        this.bar = ""; // okay
        console.log("okay"); // okay
    }
}

In your specific case, if you need ign, ignEnd, and ignSat to behave as fields exclusive to instances of MapService (not just temporary variables), declare them as type string and carry out all necessary processing within the constructor method:

export class MapService {

    ign: string;
    ignEnd: string;
    ignSat: string;

    constructor() {
        this.ign = 'https://wxs.ign.fr/secret/geoportail/wmts?';
        this.ignEnd = '&tilematrixset=PM&tilematrix={z}&tilecol={x}&tilerow={y}';
        this.ignSat = this.ign + 'layer=ORTHOIMAGERY.ORTHOPHOTOS';
        this.ignSat = this.ignSat + '&tilematrixset=PM';
        this.ignSat = this.ignSat + '&Service=WMTS';
        this.ignSat = this.ignSat + '&Request=GetTile';
        this.ignSat = this.ignSat + '&Version=1.0.0';
        this.ignSat = this.ignSat + '&Format=image%2Fjpeg' + this.ignEnd;

    }
   
}

Explore the code on TypeScript Playground

Answer №2

When it comes to TypeScript (similar to JS), declaring variables involves using the keyword let along with an optional type specifier. If you need to concatenate strings, there are a few methods to achieve this - you can use the overloaded + operator, utilize the .concat method on strings, or explore the concept of JS template literals. Below is an adjusted version of your example that functions perfectly (Playground Link):

let ign: string = 'https://wxs.ign.fr/secret/geoportail/wmts?';
let ignEnd: string = '&tilematrixset=PM&tilematrix={z}&tilecol={x}&tilerow={y}';
let ignSat: string = ign + 'layer=ORTHOIMAGERY.ORTHOPHOTOS';
ignSat = ignSat + '&tilematrixset=PM';
ignSat = ignSat + '&Service=WMTS';
ignSat = ignSat + '&Request=GetTile';
ignSat = ignSat + '&Version=1.0.0';
ignSat = ignSat + '&Format=image%2Fjpeg' + ignEnd;

If I overlooked any details, feel free to provide further clarification in your question.

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

How can I display an agm-polyline within a map in Angular 7?

I need assistance with adjusting the polylines on my map and dynamically setting the zoom level based on their size and position. Here is the code I am currently using: <agm-map style="height: 500px" [latitude]='selectedLatitude' [longitude ...

Is it possible for a voiceover artist to initiate API requests?

As I work on the registration feature of my application, I am faced with the requirement that email addresses must be unique in the database. Since I am responsible for the front-end development, I am considering creating a Value Object (VO) that can make ...

Mastering Bootstrap 4 flexbox for optimal content filling: A comprehensive guide

I am currently working on an angular app integrated with bootstrap 4. The challenge I am facing is related to the layout design. I have a fixed navbar at the top and a content area below it. Within the content area, I have a div that includes header and fo ...

Combining Observations through Conditionals

I am trying to retrieve a file through http that contains information about other files which are needed in the main file. These could be xsd files with imports, or any other type of file. You can check out the code here: https://stackblitz.com/edit/angul ...

Combining Angular Material with another CSS framework

I'm diving into my first Angular project and contemplating incorporating Angular Material. It offers an abundance of components, which aligns with my project needs. However, I've noticed a lack of grid system and utility classes within Angular Ma ...

Looking for the location of the traceResolution output?

When I enable traceResolution in my tsconfig.json file, where can I expect to see the resulting output? { "compilerOptions": { "traceResolution": true, ... The --traceResolution flag enables reporting of module resolution log messages. You ...

Angular input box with integrated datepicker icons displayed inside

Currently, I have an input field and a datepicker displayed in a row. However, I need to show an icon inside the input box instead. Here is my code: <div class="mb-2" style=" float: left;" class="example-full-width" class= ...

Angular developers are struggling to find a suitable alternative for the deprecated "enter" function in the drag and drop CDK with versions 10 and above

By mistake, I was working on an older version of Angular in StackBlitz (a code-pane platform). I came across a function called enter on GitHub, but it didn't solve my issue. I was working on a grid-based drag and drop feature that allows dragging bet ...

What is the best way to include rxjs in an npm library - as a dependency, peer dependency, or both?

After researching numerous posts and articles on dependencies versus peerDependencies, I am still not entirely certain what to do in my particular situation.... I have a library (which is published to a private npm repository) that utilizes rxjs; for exam ...

Troubleshooting issues with Angular 2+ flip animation when used in conjunction with ngIf

I am looking to create a sleek card flip animation using ngIf Link to code: https://stackblitz.com/edit/angular-card-flip-2wj64j?file=app%2Fcard%2Fcard.component.html Current animation: https://i.stack.imgur.com/CEaEc.gif ==================CODE======== ...

Ng-Select does not support disabling elements in conjunction with Bootstrap 4

After implementing ng-select (https://github.com/ng-select/ng-select) in my Angular 6 project and updating to Bootstrap 4, I encountered a problem with my custom logic for disabling elements. <ng-select style="width: 500px;" [multiple]="true" ...

Is it feasible to transform an entire Angular project into an Angular library? Learn how to successfully convert your

After successfully creating a project in Angular 13, my next goal is to transform the entire project into an Angular library. This Angular library will then be utilized in another Angular project for further development and enhancement.https://i.sstatic. ...

Prevent Click Event on Angular Mat-Button

One of the challenges I'm facing involves a column with buttons within a mat-table. These buttons need to be enabled or disabled based on a value, which is working as intended. However, a new issue arises when a user clicks on a disabled button, resul ...

Show the alias of a type in Vscode Typescript instead of its definition

Here is some code that I am working with: type Opaque<T,U> = T & {_:U}; type EKey = Opaque<number,'EKey'>; type AKey = Opaque<EKey,'AKey'>; type PKey = Opaque<AKey,'PKey'>; let a = <PKey>1; ...

Bundle multiple internal modules in typescript for easy exporting

Currently, I am exploring the idea of implementing TypeScript in node.js. I have been accustomed to using TypeScript with the ///<reference.../> syntax for internal modules. However, as projects grow larger, managing interlinking references between m ...

Can the inclusion of additional parameters compromise the type safety in TypeScript?

For demonstration purposes, let's consider this example: (playground) type F0 = (x?: string) => void type F1 = () => void type F2 = (x: number) => void const f0: F0 = (x) => console.log(x, typeof(x)) const f1: F1 = f0 const f2: F2 = f1 f ...

Having trouble navigating to a child page in Angular 4

When I try to follow the Angular routing & navigation example, I encounter an issue where my page displays as "file not found" when I route. Even when I navigate to the profile page at profile.component.html, I can see my columns, but nothing appears from ...

What is the reason for the transparency of the angular material modal?

Having an issue with my angular material modal: runProcess(assignmentNumber) { const dialogConfig = new MatDialogConfig(); dialogConfig.autoFocus = true; dialogConfig.data = { assignmentNumber } this.dialog.open(RunPostReleaseProcessCompon ...

Tips for showing various tooltip text when iterating through a list?

I am currently working on a project where I am looping through a list and attempting to assign different tooltip text to various icons. However, I am struggling with the implementation. Here is a snippet of my code: <React.Fragment key={sv.key ...

Troubleshooting routing: The Location.path() function consistently returns an empty string

I stumbled upon this tutorial which seems to be the most up-to-date example for testing routing. I'm eager to incorporate mock components in my testing strategy eventually. Unfortunately, when trying out the provided plunker, I encountered some issues ...