簡體   English   中英

錯誤TS2339:類型“字符串”上不存在屬性“默認”。**

[英]Error TS2339: Property 'Default' does not exist on type 'string'.**

我是Angular 2的新手-我的功能在提琴琴中工作正常,但是當我放入代碼庫時,我遇到了錯誤。

app / components / playing-cables / -update.ts(82,12):錯誤TS2339:類型“ jQuery”上不存在屬性“ options”。 app / components / playing-cables / -update.ts(99,21):錯誤TS2339:類型'string'上不存在屬性'Default'。

    storedPreferences.Default = {
    dropdown.options = function(data, selectedKey) {
import {Component, ElementRef, Inject, OnInit,ViewChild} from '@angular/core';
import { sportService } from '../../services/sport.service';
import {playesRightBarMultiTabComponent} from '../playing-sports/playes-right-bar-multi-tab'
import {playerComponent} from '../player/player.component';
import {ProgressCircle} from '../shared/progress/progress-circle';
import {playeService} from '../../services/playeService';
import {playingsportsEvergreen} from '../playing-sports/playe-sports-evergreen';
import {TextDecoder} from 'text-encoding-shim';
import { Router} from '@angular/router';
import {NetworkCarousel} from '../shared/content/network-carousel';
import {KendoGridComponent} from '../grid/grid.component';
import { TranslateService } from '../../translate/translate.service';
//import { ProgressCircle } from '../shared/progress/progress-circle';



@Component({
    selector: 'downlinkBulkUpdate',
    templateUrl: "./app/components/playing-cables/downlink-bulk-update.html",
})

export class downlinkBulkUpdate {
    public dataSourceVal;
    public selectedRowsUID = [];
    private count: boolean = true;
    private selectAll: boolean;


    @ViewChild(KendoGridComponent) private gridkendo: KendoGridComponent;

    constructor(public elementRef: ElementRef,private router: Router){
    }

    private kendocommand = {
        edit: { createAt: "bottom" },
        group: false,
        reorder: true,
        resize: true,
        sort: true,
        filter: { mode: "row,menu" },
        autoBind: false,
        pager: { messages: { display: "Showing {0} to {1} of {2} entries" } },
        model: {},
        columns: [],
        pagesize: 50,
        getComponentUrl: "admin/v1/lockedItems",
        saveStatus: false,
        excelfileUidName: "ViewUnlockExport",
        excelFileName: {
            fileName: "ViewUnlockExport",
            allPages: true
        },
        change: function (e) {
            console.log("kendocommand downlink-bulk-update");

            $('tr').find('[type=checkbox]').prop('checked', false);
            $('tr.k-state-selected').find('[type=checkbox]').prop('checked', true);
        },
        searchFields: []
    };

    ngOnInit() {

        $("tr th[data-field='codeLong']").hide();



        if ($('input.checkbox_check').prop('checked')) {
          //blah blah
          alert("checked");

          $("tr th[data-field='codeLong']").show();
        }


        $("#win1").hide();

        /*document.getElementById('cars').options[0].text = localStorage.getItem("someVarName") || 'unkonwn';
        var dropdown = $('<select>');
        alert("I am here dropdownmenu select"); */
            var dropdown = $('#cars');
        dropdown.options = function(data, selectedKey) {
          var self = this;
          var newOptions = '<option value="Default">Default</option>'; //create one objec to save new options
          $.each(data, function(ix, val) {
           var selected = (val == selectedKey) ? 'selected="selected"' : '';
              if (val != 'Default') {
                newOptions += '<option value="' + val + '" ' + selected + '>' + val + '</option>';
             }
            //data.push(option);
          });
          self.html(newOptions);
          self.change();
        }
        //var array = ['one', 'two', 'three'];
        var array = [];
        var storedPreferences = localStorage.getItem('preferences');
        storedPreferences = (storedPreferences) ? JSON.parse(storedPreferences) : {};
        storedPreferences.Default = {
            columns: [0,1,2],
        };
        for (var storedPreference in storedPreferences) {
            array.push(storedPreference);
        }
        dropdown.options(array, 'Default');
        //$('body').append(dropdown);
        $('#btnSubmit').on('click', function(ix, val) {
          //should clear out the current options
          //and replace with the new array
          alert("I am here dropdownmenu");
          var newArray = ['four', 'five', 'six'];
          dropdown.options(newArray, 'Default');
        });



        $("#open1").click(function() {
          alert("I am here");

          $("#win1").show().kendoWindow({
            width: "300px",
            height: "500px",
            modal: true,
            title: "Window 1"
          });
          $("#win1").data("kendoWindow").open();
        });

        $("#clearPrefrence").click(function() {
          alert("clearPrefrence");
          //localStorage.clear();
          //$("#cars option[value=volvo]").remove();
          if ($('#cars').val() != 'Default') {
            var preferences = localStorage.getItem('preferences');
            if (preferences) {
                preferences = JSON.parse(preferences);
            }
            else {
                preferences = {};
            }
              delete preferences[$('#cars').val()];
              localStorage.setItem('preferences', JSON.stringify(preferences));
              $("#cars option:selected").remove();
            $("#cars").change();
          }

        });

        $("#win1Submit").click(function() {

          var testingMickey = $("#mickey").val();
          alert("win1Submit I am here--->" + testingMickey);
          //document.getElementById('cars').options[0].text = testingMickey;

          var someVarName = testingMickey;
          var preferences = localStorage.getItem('preferences');
          if (preferences) {
              preferences = JSON.parse(preferences);
          }
          else {
              preferences = {};
          }
          var preference = {
            columns: [],
          }
          $('#rmenu input[type=checkbox]:checked').each(function() {
              preference.columns.push($(this).data('index'));
          });
          preferences[testingMickey] = preference;
          localStorage.setItem('preferences', JSON.stringify(preferences));
          var getItemsomeVarName1 = localStorage.getItem('preferences');
          getItemsomeVarName1 = JSON.parse(getItemsomeVarName1);
          var optionArray = [];
          for (var key in getItemsomeVarName1) {
              optionArray.push(key);
          }
          alert("getItemsomeVarName1 I am here--->" + getItemsomeVarName1[testingMickey].columns.length);
                dropdown.options(optionArray, testingMickey);
          $("#win1").data("kendoWindow").close();

        });




        setGrid();

         function toggleColumns() {
            $('#rmenu input[type=checkbox]').each(function(index) {
              $(this).data('index', index);
            $(this).attr('data-index', index); 
          });
          $('#rmenu input[type=checkbox]').change(function() {
            var index = $(this).data('index') + 1;
            if ($(this).is(':checked')) {
                $('.k-grid-header-wrap > table tr th:nth-child(' + index + '),table.k-focusable tr td:nth-child(' + index + ')').show();
            }
            else {
                $('.k-grid-header-wrap > table tr th:nth-child(' + index + '),table.k-focusable tr td:nth-child(' + index + ')').hide();
            }
          });

          $('select').change(function() {
              $('#rmenu input[type=checkbox]').removeAttr('checked').prop('checked', false);
              var preferences = localStorage.getItem('preferences');
            preferences = (preferences) ? JSON.parse(preferences) : {};
            var columns = [0,1,2];
            var key = $(this).val();
            if (preferences && preferences[key]) {
                columns = preferences[key].columns;
            }
            for (var a = 0; a < columns.length; a++) {
                $('#rmenu input[type=checkbox][data-index=' + a + ']').prop('checked', true).attr('checked', 'checked');
            }

            $('#rmenu input[type=checkbox]').each(function() {
                $(this).change();
            });
          });
        }

        toggleColumns();

        $('.k-grid-header').on('contextmenu', function(e) {
          e.preventDefault();
          let menu = document.getElementById("rmenu");
          menu.style.top = e.clientY + 'px';
          menu.style.left = e.clientX + 'px';

          menu.className = "show";
        });

        $(document).bind("click", function(event) {
          document.getElementById("rmenu").className = "hide";
        });



        function setGrid() {

          var ds1 = new kendo.data.DataSource({
            transport: {
              read: {
                //using jsfiddle echo service to simulate JSON endpoint
                url: "/echo/json/",
                dataType: "json",
                type: "POST",
                data: {
                  // /echo/json/ echoes the JSON which you pass as an argument
                  json: JSON.stringify({
                    "country": [{
                        "codeLong": "AUT",
                        "codeShort": "AT",
                        "name": "Austria"
                      },
                      {
                        "codeLong": "BEL",
                        "codeShort": "BE",
                        "name": "Belgium"
                      },
                      {
                        "codeLong": "BGR",
                        "codeShort": "BG",
                        "name": "Bulgaria"
                      }
                    ]
                  })
                }
              }
            },
            schema: {
              data: "country",
              model: {
                fields: {
                  codeLong: {
                    type: "string"
                  },
                  codeShort: {
                    type: "string"
                  },
                  name: {
                    type: "string"
                  }
                }
              }
            }
          });



          $("#grid1").kendoGrid({
            dataSource: ds1,
            height: 180,
            scrollable: {
              virtual: true
            },
            columns: [{
                field: "codeLong",
                title: "codeLong"
              },
              {
                field: "codeShort",
                title: "codeShort"
              },
              {
                field: "name",
                title: "name"
              }

            ]
          });
        }






        alert("downlink-bulk-update");
        console.log("downlink-bulk-update");
        let that = this;

        $(document).ready(function(){
            $(".showHideIcon").click(function(){
                alert("titleSearchResults");
            });
        });

        this.kendocommand.model = {
            id: "isSelected",
            fields: {
                contextRow: { editable: false },
                isSelected: { type: "boolean", editable: true, filterable: false },
                moduleName: { type: "string", editable: false },
                entityId: { type: "string", filterable: true, editable: false, nullable: false },
                entityName: { type: "string", editable: false, nullable: true },
                network: { type: "string", editable: false },
                entityType: { type: "string", editable: false },
                userLocked: { type: "string", editable: false },
                additionalComments: { type: "string", editable: false },
                checkOutDate: { editable: false }

            }
        };
        this.kendocommand.columns = [
            {
                field: 'contextRow',
                width: 25, locked: true
            },
            {
                field: "isSelected", filterable: false, sortable: false, editable: true, title: "Is Selected",
                template: function (container) { return that.checkboxchecker(container, "isSelected") },
                width: 30,
                headerTemplate: '<span class="displayBlock"><input type="checkbox" id="unlockCheck" /></span>'
            },
            {
                field: "moduleName",
                title: "Module Name", filterable: that.gridkendo.getAutoFilterName("contains", "moduleName"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function moduleName(options) {
                    console.log("downlink-bulk-update 2");
                    return that.gridTemplate(options, "moduleName", false);
                },
                width: 150
            }, {
                field: "entityId", title: "ID",
                filterable: that.gridkendo.getAutoFilterName("eq", "entityId"),
                headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function entityId(options) {
                    console.log("ending this.kendocommand.columns");

                    return that.gridTemplate(options, "entityId", false);
                },

                width: 90
            }, {
                field: "entityName", filterable: that.gridkendo.getAutoFilterName("contains", "entityName"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function entityName(options) {
                    return that.gridTemplate(options, "entityName", false);
                },
                title: "Name",
                width: 150
            }, {
                field: "network",
                title: "Network",
                filterable: that.gridkendo.getAutoFilterName("contains", "network"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function networkName(options) {
                    return that.gridTemplate(options, "network", false);
                },

                width: 110
            }, {
                field: "entityType",
                title: "Type", filterable: that.gridkendo.getAutoFilterName("contains", "entityType"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function entityType(options) {
                    return that.gridTemplate(options, "entityType", false);
                },
                width: 150
            }, {
                field: "userLocked",
                title: "User Locked", filterable: that.gridkendo.getAutoFilterName("contains", "userLocked"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function userLocked(options) {
                    return that.gridTemplate(options, "userLocked", false);
                },
                width: 150
            }, {
                field: "additionalComments",
                title: "Additional Comments bulk", filterable: that.gridkendo.getAutoFilterName("contains", "additionalComments"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function additionalComments(options) {
                    return that.gridTemplate(options, "additionalComments", false);
                },
                width: 200
            }, {
                field: "checkOutDate",
                title: "Date Checked Out", filterable: that.gridkendo.getAutoFilterName("contains", "checkOutDate"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function checkOutDate(options) {
                    return that.gridTemplate(options, "checkOutDate", false);
                },
                width: 200
            }
        ];

        console.log("ending this.kendocommand.columns");
    }

    private gridTemplate(options: any, fieldName: any, mandatory: any) {
        console.log("gridTemplate downlink-bulk-update");

        let value = options[fieldName];
        if (options[fieldName] == null || options[fieldName] == undefined) {
            value = "";
            options[fieldName] = " ";
        }
        options[fieldName + "FilterRowId"] = value;
        return value;
    }

    checkboxchecker(container, fieldName: any): any {
        console.log("checkboxchecker downlink-bulk-update");

        if ((this.selectedRowsUID.indexOf(container.uid) != -1) || this.selectAll) {
            container.isSelected = true;
            return '<input type="checkbox" checked="checked" style="display:block;" class="textAligncenter unlockCheckbox" #= fieldName ? \'checked="checked"\' : "false" #= fieldName/>';

        } else {
            this.count = true;
            container.isSelected = false;
            return '<input type="checkbox" style="display:block;" class="textAligncenter unlockCheckbox" #= fieldName ? \'checked="checked"\' : "false" #= fieldName/>';
        }
    }

}



‌

我想這里出現“選項”問題:

var dropdown = $('#cars');
dropdown.options = function(data, selectedKey) ...

好的,這在JavaScript中有效,但是TypeScript編譯器給您的錯誤是由於靜態類型檢查引起的。 這里的dropdown是一個jQuery對象,並且該類型(假設您使用的是jQuery的類型定義)沒有聲明options屬性,因此對其進行賦值會產生錯誤。 要允許TypeScript執行此操作,必須將typecast轉換為any ,以便該對象的行為類似於任何JavaScript對象:

var dropdown: any = $('#cars');
dropdown.options = (...)

.Default的情況下,它是相同的錯誤:您將storedPreferences聲明為

var storedPreferences = localStorage.getItem(...);

TypeScript知道localStorage.getItem返回一個string ,因此它認為storedPreferences是string類型。 在TypeScript中,您無法更改變量的類型。 實際上,這是它旨在防止的事情(這在JavaScript中很常見,並且經常導致錯誤)。 TypeScript知道該string沒有Default屬性,並指示錯誤。

為了避免這種情況,同樣,你必須聲明storedPreferences為類型的any

let storedPreferences: any = localStorage.getItem(...);

問題在於您像使用JavaScript一樣在TypeScript中進行編程,這就是為什么會出現編譯器錯誤的原因。 在TypeScript中,不能將新屬性添加到已知類型的對象。 為此,您必須事先將對象聲明為any ,以便TypeScript的行為與JavaScript完全相同(盡管這樣會失去TypeScript的優勢)。

除此之外,您應避免使用var而應使用letconst

jsfiddle中的代碼有效,因為那是JavaScript代碼,而不是TypeScript代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM